How do I find the index of an element in a table in Lua?

96 Views Asked by At

Let's say I have this code:

local testtbl = {"foo", "bar", "baz"}

How do I get the index of an element? For example:

print(indexOf(testtbl, "bar")) -- 2
1

There are 1 best solutions below

1
berriz44 On BEST ANSWER

You need to iterate over the table with ipairs, like so:

function indexOf(tbl, value)
    for i, v in ipairs(tbl) do
        if v == value then
            return i
        end
    end
end