Amir
Amir

Reputation: 1683

Returning the index of a value in a 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?

Upvotes: 9

Views: 45252

Answers (2)

MarredCheese
MarredCheese

Reputation: 20811

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'

Upvotes: 10

lhf
lhf

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

Related Questions