Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the index of a value in a Lua table

Tags:

lua

lua-table

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?

like image 257
Amir Avatar asked Jul 09 '16 13:07

Amir


People also ask

Is Lua 1 or 0 indexed?

Yes, the arrays in Lua start with index 1 as the first index and not index 0 as you might have seen in most of the programming languages.

What is an index in Lua?

In Lua, indexing generally starts at index 1. But it is possible to create objects at index 0 and below 0 as well. Array using negative indices is shown below where we initialize the array using a for loop.

What is unpack Lua?

In Lua, if you want to call a variable function f with variable arguments in an array a , you simply write f(unpack(a)) The call to unpack returns all values in a , which become the arguments to f . For instance, if we execute f = string.find a = {"hello", "ll"}

What does next return Lua?

Luanext() function returns the next index of the said table and its value associated with the table. When the next() function is called with nil value as the second argument, next returns an initial index and the associated value.


1 Answers

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"]
like image 126
lhf Avatar answered Oct 06 '22 15:10

lhf