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?
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.
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.
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"}
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.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With