• Announcement: Lua.org now officially recommends this forum as a meeting place for the Lua community
  • The forum is currently open to new registrations. The registration will close for a short period of time when reaching 500 active members, to upgrade the server resources.

metatables do not work! (1 Viewer)

olegharput

Newcomer
Joined
Mar 23, 2021
Messages
1
Reaction score
0
i can not set metatable in this code, i can not find the issue here. Need help
the Code:

Code:
local CLASS = {
   type = "CLASS",
   mt = {},
   newClass = function (self, type)
      local aaa = {}
      setmetatable(aaa, CLASS)
      for k, v in pairs(self) do
           aaa[k] = v
      end
      aaa.type = type
      aaa.super = self.type
      print("a new class named " .. type .. " created from the class " .. aaa.super)
      return aaa
   end,
   newInstance = function (self)
      local bbb = {}
      for k, v in pairs(self) do
     bbb[k] = v
      end
      print("a new instance for class " .. self.type .. " is created ")
      return bbb
   end,
   getTypeOfTheInstance = function (self)
      return self.type
   end
}

local PLAYER = CLASS:newClass("PLAYER")
local p1 = PLAYER:newInstance()
CLASS.mt.__metatable = "private"

print(getmetatable(CLASS))

return CLASS

and the output which is not true is: => Nil
i think it should be "private" but it is nil which means the metatable is not set.
What is the issue here?
 

stetre

Member
Rank: I
Joined
Jan 8, 2020
Messages
45
Reaction score
28
Location
Italy
Website
github.com
At a first glance I see a few. First of all, the metatable must be, well, a table. Secondly, to set it you must use the setmetatable function. Finally, even if you could set the metatable by assigning something directly to the __metatable field, by writing CLASS.mt.__metatable you would set the metatable of CLASS.mt, not of CLASS.
 

GavinW

Newcomer
Creator of RiscLua
Joined
Oct 21, 2020
Messages
40
Reaction score
17
Age
82
Location
UK
Website
www.wra1th.plus.com
Change the first line from
local CLASS = {
to local CLASS; CLASS = {
The variable CLASS is not in scope when you use it in line 6.
 
Top