Returning the index of a value in a Lua table
Asked Answered
M

2

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?

Majormajordomo answered 9/7, 2016 at 13:18 Comment(0)
E
10

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'
Emmaline answered 20/10, 2021 at 18:49 Comment(1)
That is really important for large tables. well writtenMajormajordomo
T
27

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"]
Tsuda answered 9/7, 2016 at 16:1 Comment(1)
That's really a smart solution.Todd
E
10

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'
Emmaline answered 20/10, 2021 at 18:49 Comment(1)
That is really important for large tables. well writtenMajormajordomo

© 2022 - 2024 — McMap. All rights reserved.