Skip to content

Collections · API

SparseSet

A set of integer ids, packed so it iterates with no gaps. Ids start at 1: removing id 0 from a set that holds ids corrupts it. Its memory follows the largest id, not how many ids it holds.

local Alive = Collections.SparseSet.new()
Alive:Add(10)
Alive:Add(20)
local Ids, Count = Alive:RawDense()
for Offset = 0, (Count - 1) * 4, 4 do
print(buffer.readu32(Ids, Offset)) -- 10, then 20
end
Member Description
.new() Creates an empty set.
:Add() Adds Id, and returns whether it was newly added.
:Remove() Removes Id by moving the last id into its place, so arrays kept in the same order can make the same move.
:Has() Whether Id is in the set.
:RawDense() Returns the packed ids and their count.
:Count() How many ids the set holds.
:Clear() Removes every id.
SparseSet The type SparseSet.new returns.
function SparseSet.new(Config: { InitialCapacity: number? }?): SparseSet

Creates an empty set.

Parameter Type Description
Config { InitialCapacity: number? }? InitialCapacity reserves room for ids up to it, 4 by default
function SparseSet:Add(Id: number): boolean

Adds Id, and returns whether it was newly added.

function SparseSet:Remove(Id: number): (number, number)

Removes Id by moving the last id into its place, so arrays kept in the same order can make the same move.

Returns Description
number the position Id held, from 1, or 0 if Id was not in the set
number the id now at that position, Id itself when it was last, or 0
function SparseSet:Has(Id: number): boolean

Whether Id is in the set.

function SparseSet:RawDense(): (buffer, number)

Returns the packed ids and their count. An Add can replace the buffer, so take it again after one.

Returns Description
buffer the ids, a u32 each from byte 0
number how many
function SparseSet:Count(): number

How many ids the set holds.

function SparseSet:Clear()

Removes every id.

export type SparseSet = {
	Add: (self: SparseSet, Id: number) -> boolean,
	Remove: (self: SparseSet, Id: number) -> (number, number),
	Has: (self: SparseSet, Id: number) -> boolean,
	RawDense: (self: SparseSet) -> (buffer, number),
	Count: (self: SparseSet) -> number,
	Clear: (self: SparseSet) -> (),
}

The type SparseSet.new returns.

© 2026 PRMS Developer