我有一个带metatable的userdata值,我想添加另一个metatable:
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())
这有可能吗?如果没有,有哪些替代方案?
答案 0 :(得分:2)
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())