【发布时间】:2021-10-09 18:59:37
【问题描述】:
我有一张桌子
myTable = {
{"apple","10"},
{"banana","20"},
{"carrot","30"}
}
是否有特定的 lua 代码可以找到“apple”的项目编号? 还是我必须检查 myTable 表中的每一项才能找到“apple”?
【问题讨论】:
标签: lua
我有一张桌子
myTable = {
{"apple","10"},
{"banana","20"},
{"carrot","30"}
}
是否有特定的 lua 代码可以找到“apple”的项目编号? 还是我必须检查 myTable 表中的每一项才能找到“apple”?
【问题讨论】:
标签: lua
如果你这样做一次,你可以使用这样的循环:
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
【讨论】: