Search for an item in a Lua list

Jay picture Jay · Mar 17, 2009 · Viewed 112.2k times · Source

If I have a list of items like this:

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

how do I check if "orange" is in this list?

In Python I could do:

if "orange" in items:
    # do something

Is there an equivalent in Lua?

Answer

Jon Ericson picture Jon Ericson · Mar 17, 2009

You could use something like a set from Programming in Lua:

function Set (list)
  local set = {}
  for _, l in ipairs(list) do set[l] = true end
  return set
end

Then you could put your list in the Set and test for membership:

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

if items["orange"] then
  -- do something
end

Or you could iterate over the list directly:

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

for _,v in pairs(items) do
  if v == "orange" then
    -- do something
    break
  end
end