【问题标题】:How do I find the number of a specific item in a lua table?如何在 lua 表中找到特定项目的编号?
【发布时间】:2021-10-09 18:59:37
【问题描述】:

我有一张桌子

myTable = {
    {"apple","10"},
    {"banana","20"},
    {"carrot","30"}
}

是否有特定的 lua 代码可以找到“apple”的项目编号? 还是我必须检查 myTable 表中的每一项才能找到“apple”?

【问题讨论】:

标签: lua


【解决方案1】:

如果你这样做一次,你可以使用这样的循环:

for i,v in ipairs(myTable) do
  if v[1] == "apple" then
    print("found apple at index " .. i)
  end
end

如果您对各种字符串多次执行此操作,您可以创建一个查找表,这样您只需遍历该表一次。

local lut = {}
for i, v in ipairs(myTable) do
  lut[v[1]] = i
end

local appleIndex = lut.apple
local carrotIndex = lut.carrot

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    相关资源
    最近更新 更多