Hi.
So I was trying something new, exchange of just setting Placement.__index = Placement
local Placement = {}
function Placement.new()
local meta = setmetatable({
__index = function(self,i,v)
self[i] = v
return self[i]
end;
__newindex = function(self,i,v)
rawset(self,i,v)
end;
},Placement)
return meta
end
function Placement:yes()
print("works!! :D")
end
return Placement
I am just testing, ngl.
This is error:
local yes = require(REPstorage.PlacementSystem.Modules.Placement)
local t = yes.new()
t:yes()
attempt to call a nil value
Do I still have to define Placement.__index = Placement ?
if __index function is defined when metatable is created
Placement.new is a constructor. Constructors used to create objects of a class. The function setmetatable is used to set the class as the metatable of the object.
local Placement = {}
Placement.__index = Placement
function Placement.new()
local placementObject = setmetatable({}, Placement)
return placementObject
end
function Placement:yes()
print("works!! :D")
end
return Placement
Also, if the value of __index is a function, the function should not have a parameter for a value. The __index function of a table’s metatable will run when a value isn’t found in the table.
If you want the objects to inherit the methods of the class, you need to define the metamethods in the class, because the class should be the metatable of its objects. You can define them in the class like you would define any other method of the class.
Here’s an example. As you can see, it is done the same way as any method of the class would be created.
function Placement:__index(i)
return Placement[i]
end
@oof0m, those functions aren’t local variables. Methods can be created with that syntax.