The following code searches an object if it cant find the value of the index in the table t
. It worked relatively well until I discovered an interesting syntax. If I use the colon operator to call a function on table t
, despite it being indexed directly from instance
, self
will be t
instead of the object that it belonged to.
local class = {}
class.__index = class
function class.new()
return setmetatable({},class)
end
function class.returnText()
return "function with dot (.) operator"
end
function class:returnText2()
-- self is actually the table 't', not the actual class object
return "function with colon (:) operator"
end
local m = {
__index = function(self,i)
return rawget(self,"instance")[i]
end,
__newindex = function(self,i,v)
rawget(self,"instance")[i] = v
end,
}
local t = setmetatable({instance = class.new()},m)
This seems to be intentional behavior on Lua’s part, but I don’t prefer it; what I really need this for is to index an instance, as such:
local m = {
__index = function(self,i)
return rawget(self,"instance")[i]
end,
__newindex = function(self,i,v)
rawget(self,"instance")[i] = v
end,
}
local t = setmetatable({instance = Instance.new("Part",workspace)},m)
I’m trying to create a dynamic object where it can index the instance while also being able to index it’s own custom members. I’m rewriting one of the bigger systems in my game and I would like to rewrite as little code as possible, which is why this object would be lovely.
Thanks