Skip to content

Instantly share code, notes, and snippets.

@TannerRogalsky
Last active June 21, 2020 04:46
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TannerRogalsky/8511136 to your computer and use it in GitHub Desktop.
Save TannerRogalsky/8511136 to your computer and use it in GitHub Desktop.
A simple set implementation in lua
local Set = {}
function Set.new()
local reverse = {}
local set = {}
return setmetatable(set, {
__index = {
insert = function(set, value)
if not reverse[value] then
table.insert(set, value)
reverse[value] = #set
end
end,
remove = function(set, value)
local index = reverse[value]
if index then
reverse[value] = nil
-- pop the top element off the set
local top = table.remove(set)
if top ~= value then
-- if it's not the element that we actually want to remove,
-- put it back into the set at the index of the element that we
-- do want to remove, replacing it
reverse[top] = index
set[index] = top
end
end
end,
contains = function(set, value)
return reverse[value] ~= nil
end
}
})
end
return Set
@LudwikJaniuk
Copy link

Using it, seems to work nicely.

@LudwikJaniuk
Copy link

Thanks for making it!

@hayrullinmar
Copy link

awesome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment