Memory
Bin
Collect connections, instances, threads and callbacks, then clean them all up with one call.
Getting it
local Bin = Engine:GetPackage("Bin")Overview
Memory leaks in Roblox usually come from forgotten connections and instances that outlive the thing they belonged to. A Bin is a place to put everything that has to be cleaned up later. When the owner goes away, one :Destroy() disconnects, destroys and cancels all of it.
local Bin = Engine:GetPackage("Bin")
local function equipSword(character: Model)
local bin = Bin.new()
local sword = bin:Add(swordTemplate:Clone())
sword.Parent = character
bin:Connect(sword.Touched, function(hit)
damage(hit)
end)
bin:Add(task.spawn(function()
while true do
task.wait(1)
sword.Glow.Enabled = not sword.Glow.Enabled
end
end))
bin:AttachTo(character) -- clean up when the character is destroyed
return bin
endThings are cleaned in reverse order of adding, and an error in one clean-up is reported as a warning without stopping the rest.
For per-player, per-character and per-round scopes with leak detection, see JunkService, which builds on the same idea.
Constructor
new
Bin.new(parent: Bin?): BinAn empty bin. With a parent, the new bin is added to the parent, so it is destroyed together with it.
Methods
Add
bin:Add<T>(item: T, cleanupMethod: string?): TAdds an item and returns it, so you can wrap a creation in bin:Add(...). How the item is cleaned up:
| Item | Clean-up |
|---|---|
| Instance | :Destroy() |
RBXScriptConnection | :Disconnect() |
| function | called |
| thread | task.cancel |
| table | the first of Destroy, Disconnect, Cancel, Clean, Stop it has |
Pass cleanupMethod to choose the method name yourself. Adding to a destroyed bin cleans the item up right away.
Connect
bin:Connect(signal, fn): connectionConnects fn to signal (an RBXScriptSignal or a Signal) and adds the connection.
Remove / RemoveNoClean
bin:Remove(item): boolean
bin:RemoveNoClean(item): booleanTakes an item out of the bin, cleaning it up (Remove) or leaving it alone (RemoveNoClean). false when the item was not in the bin.
Extend
bin:Extend(): BinCreates a child bin that is destroyed together with this one.
AttachTo
bin:AttachTo(instance: Instance): BinDestroys the bin when instance is destroyed. Attaching again replaces the previous attachment.
Clean
bin:Clean()Cleans up everything but keeps the bin usable.
Destroy
bin:Destroy()Fires Destroying, cleans up everything and marks the bin destroyed.
Properties
| Member | Description |
|---|---|
Size: number | Items in the bin. |
Destroyed: boolean | Whether :Destroy() has run. |
Destroying: Signal | Fires just before the bin cleans up on :Destroy(). |