在Lua表中返回值的索引 [英] Returning the index of a value in a Lua table
本文介绍了在Lua表中返回值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在lua中有这张桌子:
I have this table in lua:
local values={"a", "b", "c"}
如果变量等于表项之一,是否有一种方法可以返回表的索引?说
is there a way to return the index of the table if a variable equals one the table entries? say
local onevalue = "a"
如何在不迭代所有值的情况下获取表中"a"或onevalue的索引?
how can I get the index of "a" or onevalue in the table without iterating all values?
推荐答案
没有迭代就无法做到这一点.
There is no way to do that without iterating.
如果您发现自己需要经常这样做,请考虑建立一个反向索引:
If you find yourself needing to do this frequently, consider building an inverse index:
local index={}
for k,v in pairs(values) do
index[v]=k
end
return index["a"]
这篇关于在Lua表中返回值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文