0

I have a table

myTable = {
    {"apple","10"},
    {"banana","20"},
    {"carrot","30"}
}

Is there specific lua code that can find what item number "apple" is? Or would I have to check every single item in the myTable table to find "apple"?

harrry
  • 1
  • 1
  • Possible duplicate of https://stackoverflow.com/questions/7925090/lua-find-a-key-from-a-value – lhf Oct 09 '21 at 02:12

1 Answers1

2

If you do this a single time you can use a loop like this:

for i,v in ipairs(myTable) do
  if v[1] == "apple" then
    print("found apple at index " .. i)
  end
end

If you do this multiple times for various strings you can create a look up table so you only have to traverse the table once.

local lut = {}
for i, v in ipairs(myTable) do
  lut[v[1]] = i
end

local appleIndex = lut.apple
local carrotIndex = lut.carrot
Piglet
  • 27,501
  • 3
  • 20
  • 43