Skip to content

Instantly share code, notes, and snippets.

@Fizzyhex
Last active September 8, 2023 15:18
Show Gist options
  • Save Fizzyhex/000fd0068fd4b339d34fe30f26d52dd1 to your computer and use it in GitHub Desktop.
Save Fizzyhex/000fd0068fd4b339d34fe30f26d52dd1 to your computer and use it in GitHub Desktop.
Explicit Bin - requires you to pass functions or method names
local function wrapDestructorMethod(object, destructor)
return function()
destructor(object)
end
end
--- Creates a new bin object for cleanup.
local function Bin()
local contents: { [any]: boolean } = {}
-- Adds an item to the bin.
local function add(item: () -> () | { [any]: any } | Instance | RBXScriptConnection, cleanupMethodKey: any?)
if cleanupMethodKey then
local destructor = item[cleanupMethodKey]
assert(destructor, `Item {typeof(item)} "{item}" is missing key 'destructor'`)
item = wrapDestructorMethod(item, destructor)
end
contents[item] = true
--- Removes the item from the bin.
return function()
contents[item] = nil
end
end
--- Empties the contents of the bin.
local function empty()
for item in contents do
task.spawn(item)
end
table.clear(contents)
end
return add, empty
end
return Bin
@Fizzyhex
Copy link
Author

Example:

local food = { eat = function() end }
local object = { Destroy = function() end }
local connection = Instance.new("BindableEvent").Event:Connect(function() end)
local part = Instance.new("Part"))
local someCleanupFunction = function() end

binAdd(food, "eat")
binAdd(object, "Destroy")
binAdd(connection, "Disconnect")
binAdd(part, "Destroy")
binAdd(someCleanupFunction)

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