Skip to content
Engine

Memory

Pool

Reuse objects instead of creating and destroying them, for bullets, effects, UI rows and anything spawned often.

PackageShared

Getting it

local Pool = Engine:GetPackage("Pool")

Overview

Creating Instances is expensive, and destroying them creates work for the garbage collector. A pool keeps finished objects around and hands them out again. You take an item with :Get(), and give it back with :Return() when you are done instead of destroying it.

A bullet pool
local Pool = Engine:GetPackage("Pool")

local bullets = Pool.new({
	create = function()
		local bullet = bulletTemplate:Clone()
		bullet.Parent = workspace.Bullets
		return bullet
	end,
	reset = function(bullet)
		bullet.CFrame = CFrame.new(0, -1000, 0) -- park it out of sight
	end,
	destroy = function(bullet)
		bullet:Destroy()
	end,
	initial = 50,
	max = 200,
})

local function fire(origin: CFrame)
	local bullet = bullets:Get()
	bullet.CFrame = origin
	task.delay(2, function()
		bullets:Return(bullet)
	end)
end

Moving a part far away is much cheaper than changing its Parent, which is why the reset above parks bullets instead of removing them from the workspace.

Constructor

new

Pool.new(config: PoolConfig): Pool
FieldDescription
create: () -> anyMakes a new item. Required.
reset: ((item) -> ())?Prepares a returned item for its next use.
destroy: ((item) -> ())?Gets rid of an item the pool no longer keeps.
validate: ((item) -> boolean)?Checked on :Get(); items that fail (for example a part that was destroyed elsewhere) are thrown away and the next one is tried.
initial: number?Items to create up front.
max: number?Most idle items to keep. Items returned beyond this are destroyed.

Members

MemberDescription
:Get(): anyAn idle item, or a new one if none is idle.
:Return(item)Gives an item back. Errors when the item is not checked out from this pool, which catches double returns.
:Prewarm(count): numberCreates idle items ahead of time (up to Max) and returns how many were made.
:IsInUse(item): booleanWhether the item is checked out.
:Clear()Destroys every idle item. Checked-out items are untouched.
:Destroy()Clears the pool and stops it. Items returned later are destroyed straight away.
Size, FreeCount, InUseCountTotals, idle and checked out.
Max, DestroyedSettings and state.
ItemCreated: Signal<item>, ItemDestroyed: Signal<item>Fire when the pool creates or destroys an item.

Configuration

Defaults from DefaultConfiguration/Packages/Pool2 settings
SettingDefaultWhat it does
DefaultInitial0Items Pool.new() prewarms when config.initial is omitted.
DefaultMax256Idle items a pool keeps on hand when config.max is omitted.

Types

export type PoolConfig
export type Pool