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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With