gpt4 book ai didi

c - Lua - 扩展用户数据

转载 作者:行者123 更新时间:2023-12-05 01:25:40 24 4
gpt4 key购买 nike

我有一个带有元表的用户数据值,我想像这样添加另一个元表:

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

这有可能吗?如果不能,有哪些替代方案?

最佳答案

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

关于c - Lua - 扩展用户数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42975355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com