Reputation: 1683
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"
how can I get the index of "a" or onevalue in the table without iterating all values?
Upvotes: 9
Views: 45252
Reputation: 20811
The accepted answer works, but there is room for improvement:
For arrays:
-- 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
For hash tables:
-- 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'
Upvotes: 10
Reputation: 72312
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"]
Upvotes: 27