将值存储在lua的userdata对象中
我想做的是:将值存储在lua的userdata对象中,lua,Lua,我想做的是: object.foo = "bar" print(object.foo) 其中“object”是一个userdata 我已经在谷歌上搜索了一段时间(使用关键字uu newindex和lua_rawset),但我无法找到任何我想要它做的例子 我想用c++中的LuaAPI来实现这一点,让我们用lua代码来编写它,这样我们就可以对代码进行快速实验了 function create_object() -- ## Create new userdatum with a metatab
object.foo = "bar"
print(object.foo)
其中“object”是一个userdata
我已经在谷歌上搜索了一段时间(使用关键字uu newindex和lua_rawset),但我无法找到任何我想要它做的例子
我想用c++中的LuaAPI来实现这一点,让我们用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'
如果您使用userdata,您可能希望使用C API执行上述操作。然而,Lua代码应该明确哪些步骤是必要的。(newproxy(..)函数只是从Lua创建一个虚拟用户数据。)您也可以使用一个简单的表
config = { tooltype1 = "Tool",
tooltype2 = "HopperBin",
number = 5,
}
print(config.tooltype1) --"Tool"
print(config.tooltype2) --"HopperBin"
print(config.number) --5
我放弃了在C++中尝试这样做,所以我在Lua上做了。我循环遍历所有元表(_R)并分配元方法
_R.METAVALUES = {}
for key, meta in pairs(_R) do
meta.__oldindex = meta.__oldindex or meta.__index
function meta.__index(self, key)
_R.METAVALUES[tostring(self)] = _R.METAVALUES[tostring(self)] or {}
if _R.METAVALUES[tostring(self)][key] then
return _R.METAVALUES[tostring(self)][key]
end
return meta.__oldindex(self, key)
end
function meta.__newindex(self, key, value)
_R.METAVALUES[tostring(self)] = _R.METAVALUES[tostring(self)] or {}
_R.METAVALUES[tostring(self)][key] = value
end
function meta:__gc()
_R.METAVALUES[tostring(self)] = nil
end
end
问题是我应该用什么作为索引。tostring(self)仅适用于ID返回到tostring的对象。不是所有的对象都有一个ID,比如VEC3和ANG3等等。我忘记了添加我想用C++做这件事,我不确定我会怎么做。哦,我明白你的意思。我可以尝试这样做。Lua 5.2或更高版本不支持newproxy函数。字符串属性
foo
是任意的还是表示userdata对象的属性?请注意Lua\u rawset()
将跳过对元表的访问。这就是为什么它是“生的”。您希望使用任何其他操作表项的API函数,以便使用metamethods。foo只是一个变量,我用它来表示希望在lua中的userdata中存储一些内容。