Skip to content

Instantly share code, notes, and snippets.

@Fizzyhex
Last active August 10, 2023 10:59
Show Gist options
  • Save Fizzyhex/0313ed29783eac75d0b5a66247313619 to your computer and use it in GitHub Desktop.
Save Fizzyhex/0313ed29783eac75d0b5a66247313619 to your computer and use it in GitHub Desktop.
Bin
--!strict
local function wrapDestructor(object, method: (...any) -> ...any)
return function()
method(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) | RBXScriptConnection | Instance | { [any]: any },
cleanupMethodKey: any?
)
if cleanupMethodKey ~= nil then
local destructor = (item :: {})[cleanupMethodKey]
assert(
(item :: {})[cleanupMethodKey],
`Key "{cleanupMethodKey}" does not exist in item {typeof(item)} "{item}"`
)
item = wrapDestructor(item, destructor)
elseif typeof(item) == "table" then
local destructor = item.Destroy or item.destroy or item.Disconnect or item.disconnect
assert(
destructor,
"The item is missing the recognised cleanup methods (Destroy, destroy, Disconnect, disconnect) - Did you mean to specify which method to use, or provide a clean-up function?"
)
item = wrapDestructor(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
local type = typeof(item)
if type == "function" then
task.spawn(item)
elseif type == "RBXScriptConnection" then
item:Disconnect()
elseif type == "Instance" then
item:Destroy()
else
error(`Failed to remove unrecognised object {type} "{item}" from the bin`)
end
end
table.clear(contents)
end
return add, empty
end
return Bin
@Fizzyhex
Copy link
Author

Fizzyhex commented Aug 10, 2023

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)
binAdd(connection)
binAdd(part)
binAdd(someCleanupFunction)

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