Last active
August 10, 2023 10:59
-
-
Save Fizzyhex/0313ed29783eac75d0b5a66247313619 to your computer and use it in GitHub Desktop.
Bin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--!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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: