What this script does
Collect disposable tasks beside the system that owns them, then release everything through one idempotent cleanup call.
- Best for
- NPCs, UI controllers, temporary rounds, timers, prompts, and event-heavy modules.
- Language
- Luau
- Version
- 1.0.0
- Validation
- Luau runtime tested
Official Luau 0.735 parsing and strict analysis pass, and the module is covered by the pure-module runtime behavior harness.
Included behavior
- Connections, Instances, functions, and destroyable objects
- Reverse-order cleanup
- Idempotent one-time teardown
Install in the stated runtime
- 1Create a ModuleScript named CleanupBin.
- 2Paste the complete source and require it from a server or test Script in your own experience.
- 3Add each connection or temporary Instance immediately after creation, then call cleanup when the owner is removed.
Minimal usage example
local CleanupBin = require(script.Parent.CleanupBin)
local bin = CleanupBin.new()
bin:add(part.Touched:Connect(function() end))
bin:add(temporaryHighlight)
-- Later: bin:cleanup()Example inputs and result
- Supply
- Connections or temporary instances owned by your feature.
- Expect
- cleanup releases the registered resources when the feature ends.
These notes explain the example above. Read the complete source for every exported function and edge case before integrating it.
Complete source
No hidden import, minified block, or shortened loader.
--!strict
-- MIT License. Collects connections, Instances, and cleanup callbacks.
local CleanupBin = {}
CleanupBin.__index = CleanupBin
function CleanupBin.new()
return setmetatable({ tasks = {} :: { any }, cleaned = false }, CleanupBin)
end
function CleanupBin:add(taskItem: any): any
assert(not self.cleaned, "CleanupBin is already cleaned")
table.insert(self.tasks, taskItem)
return taskItem
end
local function clean(taskItem: any)
local disposable = taskItem :: any
local robloxType = typeof(disposable)
local luaType = type(disposable)
if robloxType == "RBXScriptConnection" then
disposable:Disconnect()
elseif robloxType == "Instance" then
disposable:Destroy()
elseif luaType == "function" then
disposable()
elseif luaType == "table" then
local object = disposable
local destroy = object.destroy or object.Destroy
if type(destroy) == "function" then
local callback = destroy :: (any) -> ()
callback(object)
end
end
end
function CleanupBin:cleanup()
if self.cleaned then return end
self.cleaned = true
for index = #self.tasks, 1, -1 do clean(self.tasks[index]) end
table.clear(self.tasks)
end
return CleanupBin
d053338e3985ef7b62684770605d782e6625947f15bdc27748a0d8a25c57b883Outside this script’s scope
- Discover leaked objects automatically
- Clean tasks that were never added
Found a problem or a better approach?
Tell us what failed, what you expected, and whether the issue happened in the Luau CLI or Roblox Studio. Suggestions for clearer types, safer server checks, or a more useful API are welcome.