-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSet.lua
36 lines (36 loc) · 1002 Bytes
/
Set.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
local Set = {}
Set.new = function(class)
return setmetatable({}, {__index=class, __tostring=class.tostring})
end
Set.insert = function(self, value)
self[value] = self[value] or ( self:count() + 1 )
return self[value]
end
Set.remove = function(self, value)
self[value] = nil
end
Set.count = function(self)
local count = 0
table.foreach(self, function()
count = count + 1
end)
return count
end
Set.index = function(self, value)
return self[value]
end
Set.tostring = function(self, visit)
local check = visit or Set:new()
local index = check:index(self)
if index then
return string.format('<table %d>', index)
else
local result = nil
local index = check:insert(self)
table.foreach(self, function(index, value)
result = ( result and result .. ', ' or '' ) .. ( type(value) == type(self) and getmetatable(value).__tostring or tostring ) ( value, check )
end)
return string.format('Set<table %d> {%s}', index, result or '')
end
end
return Set