9

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?

Amir
  • 1,667
  • 3
  • 23
  • 42

3 Answers3

24

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"]
lhf
  • 70,581
  • 9
  • 108
  • 149
5

The accepted answer works, but there is room for improvement:

  • Why not exit the loop once the element is found? And why bother copying the entire source table into a new throwaway table?
  • Usually, this sort of function returns the first array index with that value, not an arbitrary array index with that value.

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'
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
0

If you use Lua for Roblox development, you can use the table.find method:

print(table.find({'a', 'b', 'c'}, 'b'))
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
Zeyad Shaban
  • 896
  • 1
  • 8
  • 23