轻用户数据作为表键
我正在使用 Lua/C 绑定,并且对存储在 lua 表中的轻用户数据对象存在问题。在下面的示例中,我使用一些数据从 C 调用“myfunction”,然后使用这些数据通过我的函数“net.connection(v)”分配一个新对象(在 C 中),该函数使用 lua_newuserdata() 返回对象结果。我尝试使用该值作为表“mytable”的键。当我调用“myfunction”,创建新对象并将其存储在我的表中时,它似乎很好,因为我存储到表中的值就是“print”给我的值。
mytable = {}
function action(obj)
print(mytable[obj])
end
function myfunction(data)
for k,v in pairs(data) do
theObj = net.connection(v)
mytable[theObj] = "test string"
print(mytable[theObj]) --Prints 'test string'
end
end
然而,在稍后的时间点,我想使用相同的对象指针(上面的函数“action”)查找这些数据,但总是得到 nil。 (theObj 和 obj)的指针地址是相同的,当我打印出表的内容(键,值)时,表似乎包含指向我的用户数据的指针和正确的值,但是当我使用参数 (obj),我无法从表中检索值。对于函数“action”,我使用push_lightuserdata 将用户数据推送到堆栈上。
以这种方式使用 push_lightuserdata 是否存在任何可能导致此问题的微妙之处?
根据 this 链接,使用轻用户数据作为表键就可以了......
I'm working with Lua/C bindings and am having an issue with objects stored in a lua table that are light user data. In the example below, I'm calling 'myfunction' from C with some data that is then used to allocate a new object (in C) via my function "net.connection(v)", which uses
lua_newuserdata() to return the object result. I try to use this value as a key into a table 'mytable'. When I call 'myfunction', create my new object, and store it in my table, it appears to be fine, as the value I store into the table is what the 'print' gives me.
mytable = {}
function action(obj)
print(mytable[obj])
end
function myfunction(data)
for k,v in pairs(data) do
theObj = net.connection(v)
mytable[theObj] = "test string"
print(mytable[theObj]) --Prints 'test string'
end
end
However, at a later point in time, I want to look up this data using the same object pointer (function 'action' above), but always get nil. The pointer addresses of (theObj and obj) are the same, and when I print out the contents of the table (keys, values) it appears that the table contains both a pointer to my userdata and the proper value, but when I use the argument (obj), I can't retrieve a value from the table. In the case of the function 'action', I'm pushing the user data onto the stack with push_lightuserdata.
Are there any subtleties to using push_lightuserdata in this way that could be causing this issue?
Accoring to this link, using light user data as a table key is fine...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
用户数据和轻用户数据是 Lua 中两种不同的类型。您将一个用户数据作为键放入表中,然后尝试使用少量用户数据来查找它。那是行不通的。您需要使用相同的类型。
由于您将
net.connection
创建为用户数据,因此您需要将其保存在某个表中,以便稍后可以从 C 中找到它。Userdata and light userdata are two distinct types in Lua. You are putting a userdata in the table as the key, and then trying to find it with a light userdata. That won't work. You need to use the same types.
Since you are creating the
net.connection
as a userdata, you'll need to keep it in a table somewhere so you can find it later from C.