Skip to content
Engine

Memory

Bin

Collect connections, instances, threads and callbacks, then clean them all up with one call.

PackageShared

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
end

Things 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?): Bin

An 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?): T

Adds an item and returns it, so you can wrap a creation in bin:Add(...). How the item is cleaned up:

ItemClean-up
Instance:Destroy()
RBXScriptConnection:Disconnect()
functioncalled
threadtask.cancel
tablethe 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): connection

Connects fn to signal (an RBXScriptSignal or a Signal) and adds the connection.

Remove / RemoveNoClean

bin:Remove(item): boolean
bin:RemoveNoClean(item): boolean

Takes 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(): Bin

Creates a child bin that is destroyed together with this one.

AttachTo

bin:AttachTo(instance: Instance): Bin

Destroys 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

MemberDescription
Size: numberItems in the bin.
Destroyed: booleanWhether :Destroy() has run.
Destroying: SignalFires just before the bin cleans up on :Destroy().