# Using curly braces
my_set = {1, 2, 3, 4}
my_set.add(5)
my_set.remove(3)
print(1 in my_set) # Output: True
print(6 in my_set) # Output: False
for element in my_set:
print(element)
https://www.lua.org/pil/11.5.html
function Set (list)
local set = {}
for _, l in ipairs(list) do set[l] = true end
return set
end
reserved = Set{"while", "end", "function", "local", }
-- file : set-impl.lua
function SetBelongs(myset, item)
return myset[item] and true or false
end
function SetAdd(myset, item)
myset[item] = true
return myset
end
function SetDel(myset, item)
myset[item] = nil
return myset
end
function SetNew(list)
local set = {}
for _, value in ipairs(list) do
set[value] = true
end
return set
end
function SetList(myset)
for key, value in pairs(myset) do
print(key)
end
end
-- file : set-use.lua
require("set-impl")
local function TestSetFunctions()
print("# initial set :")
local myset = SetNew{ 1, 2, 3, 4, }
SetList(myset)
print("# add 5 to set :")
myset = SetAdd(myset, 5)
SetList(myset)
print("# remove 3 from set :")
myset = SetDel(myset, 3)
SetList(myset)
print("# belongs to set or not :")
print(SetBelongs(myset, 1) and "1 belongs" or "1 does not belong")
print(SetBelongs(myset, 6) and "6 belongs" or "6 does not belong")
end
TestSetFunctions()
# initial set :
1
2
3
4
# add 5 to set :
1
2
3
4
5
# remove 3 from set :
1
2
4
5
# belongs to set or not :
1 belongs
6 does not belong