0

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
2
  • @Aki i answered my own question, q&a-style, i kind of know Commented Sep 8, 2023 at 16:56
  • If you know and there is already answer on SO, then why? Commented Sep 8, 2023 at 17:12

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Note: This will only work if tbl is a sequence (has only consecutive integer keys starting at 1). I'd probably use pairs for a more general solution which will still work for sequences.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.