【问题标题】:Lua - Extending userdataLua - 扩展用户数据
【发布时间】:2017-03-23 21:24:40
【问题描述】:

我有一个带有元表的 userdata 值,我想像这样添加另一个元表:

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())

这有可能吗?如果没有,有什么替代方案?

【问题讨论】:

    标签: c lua


    【解决方案1】:
    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())
    

    【讨论】:

      猜你喜欢
      • 2018-09-12
      • 2014-01-23
      • 2020-09-10
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      相关资源
      最近更新 更多