How can I find the number of an item in a table

Hey developers, so I was wondering how I could find out the number of a value in a table, for example; table[1] would return the first value, but how can you work out what number each value has?

local function getIndexFromValue(t, value)
  for i, v in pairs(t) do
    if v == value then
      return i
    end
 end
end

local yes = {
 'oksir',
 true
}

print(getIndexFromValue(yes, true))

it would print 2

2 Likes

This is literally what table.find() is for.

table.find(t, value)

It works the same as what @legs_v made, but it does not require you to paste the function in ever script you want to use this in.

An example of table.find() being used:

local items = { 
   "apple", 
   "orange", 
   "pear", 
   "banana" 
}

print(table.find(items, "apple")) -- 1
print(table.find(items, "citrus")) -- nil
2 Likes

Oh right. I thought table.find only returned the index number even if the index is a string.