Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for an item in a Lua list

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?

like image 287
Jay Avatar asked Mar 17 '09 21:03

Jay


1 Answers

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 
like image 150
Jon Ericson Avatar answered Oct 15 '22 06:10

Jon Ericson