local set = {} -- empty set
Create a set with elements by setting their value to true
:
local set = {pear=true, plum=true}
-- or initialize by adding the value of a variable:
local fruit = 'orange'
local other_set = {[fruit] = true} -- adds 'orange'
add a member by setting its value to true
set.peach = true
set.apple = true
-- alternatively
set['banana'] = true
set['strawberry'] = true
set.apple = nil
Using nil
instead of false
to remove 'apple' from the table is preferable because it will make iterating elements simpler. nil
deletes the entry from the table while setting to false
changes its value.
if set.strawberry then
print "We've got strawberries"
end
for element in pairs(set) do
print(element)
end