Skip to content

Instantly share code, notes, and snippets.

@bmwalters
Last active November 20, 2016 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmwalters/2193be296349df160e570914662a6369 to your computer and use it in GitHub Desktop.
Save bmwalters/2193be296349df160e570914662a6369 to your computer and use it in GitHub Desktop.
Yet another Lua Set class
local SET = {}
if gmod then debug.getregistry().Set = SET end
function SET:Add(item)
self._data[item] = true
end
function SET:Remove(item)
self._data[item] = nil
end
function SET:Contains(item)
return self._data[item] == true
end
function SET:Iter()
return next, self._data
end
function SET:Count()
local len = 0
for _ in self:Iter() do
len = len + 1
end
return len
end
SET.__len = SET.Count
function SET:Unioned(other)
local out = Set()
for item in other:Iter() do
out:Add(item)
end
for item in self:Iter() do
out:Add(item)
end
return out
end
function SET:Subtracted(other)
local out = Set()
for item in self:Iter() do
if not other:Contains(item) then
out:Add(item)
end
end
return out
end
function SET:Intersected(other)
local out = Set()
for item in self:Iter() do
if other:Contains(item) then
out:Add(item)
end
end
return out
end
-- syntactic sugar for checking membership
function SET:__index(k)
return SET[k] or self._data[k]
end
function SET:__tostring()
return string.format("set (%d values)", self:Count())
end
function Set(...)
local self = setmetatable({ _data = {} }, SET)
for _, item in pairs({ ... }) do
self:Add(item)
end
return self
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment