Lua 如何通过表值检索表行?
示例:
mytable = {{id=100,wordform="One Hundread"},{id=200,wordform="Two Hundread"}}
我希望能够根据 id 访问行来执行以下操作:
mynum = 100
print ("The value is " .. mytable[mynum].wordform)
这里的要点是我希望能够设置索引值,以便我可以在以后按预期检索关联值,就像我可能会做的那样java 哈希图。
Example:
mytable = {{id=100,wordform="One Hundread"},{id=200,wordform="Two Hundread"}}
I want to be able to access the row based on the id to do something like this:
mynum = 100
print ("The value is " .. mytable[mynum].wordform)
The main point here is I want to be able to set the index value so I can predictably retrieve the associated value later as I might do with a java hashmap.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
理想情况下,你的表应该只使用 ID 作为键:
如果你的表是列表形式,你可以很容易地将其转换为 ID 形式:
使用 Lua 表的哈希部分绝对比在线性时间内循环列表条目更可取,如下所示Renshaw 的回答表明(它隐藏在元表后面的事实可能隐藏了糟糕的性能,并欺骗读者相信这里正在发生哈希索引操作)。
此外,该答案甚至无法正常工作,因为列表部分也使用整数键;作为有效列表部分索引的 ID 可能会返回错误的元素。您必须使用函数而不是元表。
Ideally your table should just use the ID as key:
If your table is in list form, you can convert it to ID form rather easily:
Using the hash part of a Lua table is definitely preferable over looping over the list entries in linear time as Renshaw's answer suggests (the fact that it's hidden behind a metatable may hide the poor performance and trick the reader into believing a hash indexing operation is taking place here though).
Furthermore, that answer won't even work correctly, as the list part uses integer keys as well; IDs that are valid list part indices would possibly return the wrong element. You'd have to use a function instead of a metatable.
你可以使用
metatable
然后
you can use
metatable
then