Lua - user data extension

I have a userdata value with a meta meta and I would like to add another meta meta like this:

local obj = Game:create_object() --Obj now contains userdaa
print(obj:get_x()) --Use method in metatable of obj

--I would like to do something like this:
local mt = {name = "test"}
mt.__index = mt
setmetatable(obj, mt)
print(obj.name)

--And still have the methods from the beginning
print(obj:get_x())

      

Is this possible anyway? If not, what are the alternatives?

+3


source to share


1 answer


local obj = Game:create_object() --Obj now contains userdaa
print(obj:get_x()) --Use method in metatable of obj

local new_fields = {name = "test"}
local mt = {}
for k, v in pairs(getmetatable(obj)) do
   mt[k] = v
end
new_fields.__index = mt.__index
mt.__index = setmetatable(new_fields, new_fields)
setmetatable(obj, mt)

--And still have the methods from the beginning
print(obj.name)
print(obj:get_x())

      



+2


source







All Articles