Lua 如何通过表值检索表行?

发布于 2025-01-16 23:38:52 字数 292 浏览 1 评论 0原文

示例:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伴我心暖 2025-01-23 23:38:52

理想情况下,你的表应该只使用 ID 作为键:

local mytable = {[100] = {wordform = "One hundred"}, [200] = {wordform = "Two hundred"}}
print("The value is " .. mytable[100].wordform)

如果你的表是列表形式,你可以很容易地将其转换为 ID 形式:

local mytable_by_id = {}
for _, item in pairs(mytable) do mytable_by_id[item.id] = item end

使用 Lua 表的哈希部分绝对比在线性时间内循环列表条目更可取,如下所示Renshaw 的回答表明(它隐藏在元表后面的事实可能隐藏了糟糕的性能,并欺骗读者相信这里正在发生哈希索引操作)。

此外,该答案甚至无法正常工作,因为列表部分也使用整数键;作为有效列表部分索引的 ID 可能会返回错误的元素。您必须使用函数而不是元表。

Ideally your table should just use the ID as key:

local mytable = {[100] = {wordform = "One hundred"}, [200] = {wordform = "Two hundred"}}
print("The value is " .. mytable[100].wordform)

If your table is in list form, you can convert it to ID form rather easily:

local mytable_by_id = {}
for _, item in pairs(mytable) do mytable_by_id[item.id] = item end

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.

苍景流年 2025-01-23 23:38:52

你可以使用metatable

setmetatable(mytable, {__index = function(tbl, id)
    for _, item in pairs(tbl) do
      if type(item) == "table" and item.id == id then
        return item
      end
    end
end})

然后

mynum = 100
print ("The value is " .. mytable[mynum].wordform) -- The value is One Hundread

you can use metatable

setmetatable(mytable, {__index = function(tbl, id)
    for _, item in pairs(tbl) do
      if type(item) == "table" and item.id == id then
        return item
      end
    end
end})

then

mynum = 100
print ("The value is " .. mytable[mynum].wordform) -- The value is One Hundread
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文