我想做的是:
object.foo = "bar"
print(object.foo)
其中“对象”是用户数据。
我已经用谷歌搜索了一段时间(使用关键字 __newindex 和 lua_rawset),但我找不到任何可以实现我想要的功能的示例。
我想用c++中的lua api来做到这一点
最佳答案
让我们用 Lua 代码编写它,以便我们可以用代码快速进行实验
function create_object()
-- ## Create new userdatum with a metatable
local obj = newproxy(true)
local store = {}
getmetatable(obj).__index = store
getmetatable(obj).__newindex = store
return obj
end
ud = create_object()
ud.a = 10
print(ud.a)
-- prints '10'
如果您使用用户数据,您可能希望使用 C API 执行上述操作。然而 Lua 代码应该清楚地说明哪些步骤是必要的。 (newproxy(..)
函数只是从 Lua 创建一个虚拟用户数据。)
关于lua - 将值存储在 lua 的 userdata 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3541839/