我在lua中有这个表:
local values={"a", "b", "c"}
Run Code Online (Sandbox Code Playgroud)
如果变量等于表条目中的一个,有没有办法返回表的索引?说
local onevalue = "a"
Run Code Online (Sandbox Code Playgroud)
如何在不迭代所有值的情况下获取表中"a"或onevalue的索引?
没有迭代就没有办法做到这一点.
如果您发现自己需要经常这样做,请考虑构建反向索引:
local index={}
for k,v in pairs(values) do
index[v]=k
end
return index["a"]
Run Code Online (Sandbox Code Playgroud)
接受的答案有效,但还有改进的空间:
对于数组:
-- Return the first index with the given value (or nil if not found).
function indexOf(array, value)
for i, v in ipairs(array) do
if v == value then
return i
end
end
return nil
end
print(indexOf({'b', 'a', 'a'}, 'a')) -- 2
Run Code Online (Sandbox Code Playgroud)
对于哈希表:
-- Return a key with the given value (or nil if not found). If there are
-- multiple keys with that value, the particular key returned is arbitrary.
function keyOf(tbl, value)
for k, v in pairs(tbl) do
if v == value then
return k
end
end
return nil
end
print(keyOf({ a = 1, b = 2 }, 2)) -- 'b'
Run Code Online (Sandbox Code Playgroud)