tecs.ecs#

Overview#

Functions#

Componentcomptime#

@comptime function(info: types.derive.Info): types.derive.Result<derived.Value>
@comptime

Marks a record or struct as an ECS component and selects its physical storage.

Arguments#

info - types.derive.Info

The declaration being derived.

Returns#

types.derive.Result<derived.Value>

Returns its metadata and reusable initializer recipe.

Raises#

Type Condition
string when the declaration cannot supply a reusable initializer.

declaredComponentsfunction#

function(): {[string]: Component}

Returns a fresh snapshot of every declared component.

Returns#

{[string]: Component}

the caller-owned name-to-component table

definitionfunction#

function<T is derived.Value>(declaration: Type<T>): Component

Returns the registered definition for a derived component declaration.

Type parameters#

Name Description
T

Arguments#

declaration - Type<T>

The component declaration to register if necessary.

Returns#

Component

Returns its process-wide identity and storage metadata.

findComponentByIdfunction#

function(id: integer): Component?

Returns a registered component by numeric id.

Arguments#

id - integer

the process-wide component id

Returns#

Component?

the component, or nil when the id is unknown

findComponentByNamefunction#

function(name: string): Component?

Returns a registered component by name.

Arguments#

name - string

the process-wide component name

Returns#

Component?

the component, or nil when the name is unknown

newComponentfunction#

function<T>(
    witness: Type<T>,
    options: ComponentOptions<T>?
): ComponentDefinition<T>

Registers a declaration with managed or native columns selected from its layout. The default identity of a derived declaration is cached. Configure it before its first use, or supply a distinct name to create another identity.

Type parameters#

Name Description
T

Arguments#

witness - Type<T>
The record or struct declaration whose values this definition stores.
options - ComponentOptions<T>?
The optional identity, constructor, defaults and snapshot policy.

Returns#

ComponentDefinition<T>

Returns a callable definition with the declaration's exact column type.

Raises#

Type Condition
string when the name is empty or already belongs to another definition.
string when a declaration has neither an initializer nor an explicit constructor.
string when a native layout is unsupported or snapshot codecs are incomplete.
string when a requirement is unregistered or names an untargeted relationship.

newTagComponentfunction#

function(options: TagComponentOptions): Component

Creates and registers a marker component with no per-entity value.

Arguments#

options - TagComponentOptions

the process-unique component name and snapshot policy

Returns#

Component

the registered tag component

Raises#

Type Condition
string when the name is empty or already registered
string when a requirement is unregistered or names an untargeted relationship.

newWorldfunction#

function(config: WorldConfig?): World

Creates an independent empty world carrying the builtin systems.

The world arrives with tecs.SnapshotTransforms, ttl, RelativeTransform2D and RelativeTransformDirtySampler already registered, which is what makes a TTL expire and a RelativeTransform2D move its entity without a game installing anything.

Arguments#

config - WorldConfig?

the world settings, or nil for defaults

Returns#

World

the empty world

Raises#

Type Condition
string when a capacity or fixed-clock option is invalid

Relationshipcomptime#

@comptime function(info: types.derive.Info): types.derive.Result<derived.Edge>
@comptime

Marks a target-bearing record or struct as an ECS relationship.

Arguments#

info - types.derive.Info

The declaration being derived.

Returns#

types.derive.Result<derived.Edge>

Returns its metadata and reusable initializer recipe.

Raises#

Type Condition
string when the target, policies or initializer are invalid.

targetingfunction#

function<T is derived.Edge>(
    relationship: Type<T>,
    target: integer
): ComponentDefinition<T>

Selects the typed dense column for one target of a derived relationship.

Type parameters#

Name Description
T

Arguments#

relationship - Type<T>
The derived edge declaration.
target - integer
The committed or reserved target identifier.

Returns#

ComponentDefinition<T>

Returns a reusable selector with the edge's exact physical column type.

Raises#

Type Condition
string when the relationship is sparse or the target is invalid.

Types#

Archetyperecord#

record Archetype

A dense archetype returned by query iteration.

Members#

idfield#

id: integer

signaturefield#

signature: string

componentIdsfield#

componentIds: {[integer]: boolean}

componentsfield#

components: {Component}

entitiesfield#

entities: DoubleArray

columnsfield#

columns: {[integer]: any}

Engine-owned. Holds heterogeneous managed arrays or native C arrays. This storage seam is public for world internals; game code uses get or getMut.

addEntityObservermethod#

function(self: Archetype, observer: ArchetypeEntityObserver)

Registers publication callbacks without replaying existing rows.

Arguments#
self - Archetype
The archetype to observe.
observer - ArchetypeEntityObserver
The callbacks retained until destruction.

structuralDescribedmethod#

function(self: Archetype, count: integer): boolean

Reports whether row residue completely describes changes since a structural count.

Arguments#
self - Archetype
The archetype to inspect.
count - integer
The consumer's previous structural count.
Returns#
boolean

Returns false when a full refresh is necessary.

structuralAddedmethod#

function(self: Archetype): integer

Returns the first appended one-based row in this dirty window, or zero.

Arguments#
self - Archetype

The archetype to inspect.

Returns#
integer

Returns the suffix start, which may exceed the current row count.

structuralTouchedmethod#

function(self: Archetype): ({integer}, integer)

Returns the reused swap-pop row residue for this dirty window.

Arguments#
self - Archetype

The archetype to inspect.

Returns#
{integer}
Returns the borrowed row list and its live prefix length.
integer

valueCountmethod#

function(self: Archetype): integer

Counts explicitly tracked value writes, excluding structural changes.

Arguments#
self - Archetype

The archetype to inspect.

Returns#
integer

Returns the monotonically increasing counter.

trackValueCountmethod#

function(self: Archetype, component: components.Selector)

Enables aggregate value counting for one present component.

Arguments#
self - Archetype
The archetype to track.
component - components.Selector
The column whose future writes contribute to valueCount.

setmethod#

function(self: Archetype, row: integer, input: ComponentInput)

Writes one existing component without changing row membership.

Arguments#
self - Archetype
The archetype to update.
row - integer
The one-based live row.
input - ComponentInput
The constructed component value.
Raises#
Type Condition
string when the row or component is absent, or the input changes relationship membership or a durable key.

getmethod#

get(self, component)#
function<C is Component>(self: Archetype, component: C): C.Column?
Type parameters#
Name Description
C
Arguments#
self - Archetype
component - C
Returns#
C.Column?
get(self, component)#
function<T is ComponentValue>(
    self: Archetype,
    component: Type<T>
): derived.Column(T, RelationshipPayload)?
Type parameters#
Name Description
T
Arguments#
self - Archetype
component - Type<T>
Returns#
derived.Column(T, RelationshipPayload)?

getMutmethod#

getMut(self, component)#
function<C is Component>(self: Archetype, component: C): C.Column?
Type parameters#
Name Description
C
Arguments#
self - Archetype
component - C
Returns#
C.Column?
getMut(self, component)#
function<T is ComponentValue>(
    self: Archetype,
    component: Type<T>
): derived.Column(T, RelationshipPayload)?
Type parameters#
Name Description
T
Arguments#
self - Archetype
component - Type<T>
Returns#
derived.Column(T, RelationshipPayload)?

isComponentDirtymethod#

function(self: Archetype, component: components.Selector): boolean
Arguments#
self - Archetype
component - components.Selector
Returns#
boolean

anyComponentDirtymethod#

function(self: Archetype): boolean
Arguments#
self - Archetype
Returns#
boolean

markComponentDirtymethod#

function(self: Archetype, component: components.Selector)
Arguments#
self - Archetype
component - components.Selector

markAllComponentsDirtymethod#

function(self: Archetype)
Arguments#
self - Archetype

clearDirtyComponentsmethod#

function(self: Archetype)
Arguments#
self - Archetype

dirtyComponentsmethod#

function(self: Archetype): function(): Component?
Arguments#
self - Archetype
Returns#
function(): Component?

structuralCountmethod#

function(self: Archetype): integer

Returns the structural write count, which survives dirty-bit clearing.

Arguments#
self - Archetype
Returns#
integer

writeCountmethod#

function(self: Archetype, component: components.Selector): integer

Returns one column's write count, which survives dirty-bit clearing.

Arguments#
self - Archetype
component - components.Selector
Returns#
integer

forEachRelationshipmethod#

Iterates an entity row's edges in target order.

forEachRelationship(self, relationship, row, callback)#
function<C is Component>(
    self: Archetype,
    relationship: C,
    row: integer,
    callback: function(value: C.Value)
)
Type parameters#
Name Description
C
Arguments#
self - Archetype
The archetype containing the row.
relationship - C
The relationship definition or a target-specific component.
row - integer
The one-based row to inspect.
callback - function(value: C.Value)
The callback receiving each live edge value.
forEachRelationship(self, relationship, row, callback)#
function<T is RelationshipPayload>(
    self: Archetype,
    relationship: Type<T>,
    row: integer,
    callback: function(value: T)
)
Type parameters#
Name Description
T
Arguments#
self - Archetype
The archetype containing the row.
relationship - Type<T>
The relationship definition or a target-specific component.
row - integer
The one-based row to inspect.
callback - function(value: T)
The callback receiving each live edge value.

getFirstRelationshipmethod#

Returns the first edge in target order.

getFirstRelationship(self, relationship, row)#
function<C is Component>(
    self: Archetype,
    relationship: C,
    row: integer
): C.Value?
Type parameters#
Name Description
C
Arguments#
self - Archetype
The archetype containing the row.
relationship - C
The relationship to inspect.
row - integer
The one-based entity row.
Returns#
C.Value?

Returns the live edge value, or nil when no edge exists.

getFirstRelationship(self, relationship, row)#
function<T is RelationshipPayload>(
    self: Archetype,
    relationship: Type<T>,
    row: integer
): T?
Type parameters#
Name Description
T
Arguments#
self - Archetype
The archetype containing the row.
relationship - Type<T>
The relationship to inspect.
row - integer
The one-based entity row.
Returns#
T?

Returns the live edge value, or nil when no edge exists.

ArchetypeCreatedrecord#

record ArchetypeCreated
@derive(events.event) @event(name="ArchetypeCreated")

Reports newly registered archetypes at the world's zero address.

Members#

constructors

fields

constructorconstructor#

function(archetype: Archetype): tecs.ecs.ArchetypeCreated

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
archetype - Archetype

Required. Read-only. Identifies the new archetype, available for lifecycle observation.

Returns#
tecs.ecs.ArchetypeCreated

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").ArchetypeCreated(
    archetype = archetype
)

archetypefield#

archetype: Archetype

Read-only. Identifies the new archetype, available for lifecycle observation.

ArchetypeEntityObserverinterface#

interface ArchetypeEntityObserver

Receives row and lifetime notifications from one archetype.

Members#

onEntitiesAddedfield#

onEntitiesAdded: (
    function(
        self: ArchetypeEntityObserver,
        value: Archetype,
        first: integer,
        last: integer,
        count: integer,
        source: Archetype?
    )
)?

Caller-writable. Receives initialized one-based rows and their previous archetype.

onEntitiesRemovedfield#

onEntitiesRemoved: (
    function(
        self: ArchetypeEntityObserver,
        value: Archetype,
        first: integer,
        last: integer,
        count: integer,
        target: Archetype?
    )
)?

Caller-writable. Receives still-readable one-based rows and their destination.

onEntityMovefield#

onEntityMove: (function(self: ArchetypeEntityObserver, value: Archetype, entity: integer, fromRow: integer, toRow: integer))?

Caller-writable. Receives a swap-pop relocation with zero-based row indices.

onActivatedfield#

onActivated: (function(self: ArchetypeEntityObserver, value: Archetype))?

Caller-writable. Runs when the archetype becomes nonempty.

onDeactivatedfield#

onDeactivated: (function(self: ArchetypeEntityObserver, value: Archetype))?

Caller-writable. Runs when the archetype becomes empty.

onArchetypeDestroyedfield#

onArchetypeDestroyed: (function(self: ArchetypeEntityObserver, value: Archetype))?

Caller-writable. Runs before maintenance permanently unregisters the archetype.

BatchCallbacktype#

type BatchCallback = function(candidate: Archetype, firstRow: integer, lastRow: integer, count: integer)

Initializes or updates a contiguous one-based archetype row range at a barrier.

Arguments#

candidate - Archetype
firstRow - integer
lastRow - integer
count - integer

Bundlerecord#

record Bundle

A reusable world-bound spawn shape.

Members#

instance methods

fields

namefield#

name: string

requiredfield#

required: {string}

defaultedfield#

defaulted: {string}

spawnmethod#

function(self: Bundle, ...: ComponentInput): integer
Arguments#
self - Bundle
... - ComponentInput
Returns#
integer

BundleDefinitiontype#

type BundleDefinition = {
    required: {components.Selector}?,
    with: {[components.Selector]: true | BundleFactory}?
}

Required and defaulted components for a bundle.

Members#

fields

requiredfield#

required: {components.Selector}?

withfield#

with: {[components.Selector]: true | BundleFactory}?

Componentinterface#

interface Component

A process-wide component definition.

Members#

Valuefield#

Value: associatedDecl

Columnfield#

Column: associatedDecl

componentIdfield#

componentId: integer

componentNamefield#

componentName: string

storageTypefield#

storageType: string

transientfield#

transient: boolean

ComponentDefinitioninterface#

interface ComponentDefinition<T> is Component

A named definition with its column type selected from the value declaration.

Type parameters#

Name Description
T

Members#

implements

static methods

metamethods

fields

Valuefield#

Value: associatedDecl

Columnfield#

Column: associatedDecl

constructmethod#

function(...: any): T
Arguments#
... - any
Returns#
T

defaultFactorymethod#

function(): T
Returns#
T

snapshotSavemethod#

function(value: T): any
Arguments#
value - T
Returns#
any

snapshotLoadmethod#

function(value: any, exclusive world: any): T
Arguments#
value - any
exclusive world - any
Returns#
T

__callmetamethod#

function(
    self,
    ...: any
): tecs.gfx.models.BoundsInput<T, ComponentDefinition<T>>
Arguments#
? - self
... - any
Returns#
tecs.gfx.models.BoundsInput<T, ComponentDefinition<T>>

ComponentInputtype#

type ComponentInput = Component
    | Type<ComponentValue>
    | ComponentValue
    | ScalarInstance<any>
    | TableInstance<any>
    | tecs.gfx.models.BoundsInput<any, any>
    | RelationshipInstance
    | RelationshipBatch

A component definition or constructed value accepted by a mutation.

ComponentOptionstype#

type ComponentOptions<T> = {
    name: string?,
    construct: (function(...: any): T)?,
    default: (function(): T)?,
    transient: boolean?,
    requires: {ComponentInput}?,
    save: (function(value: T): any)?,
    load: (function(value: any): T)?,
    deserialize: (function(exclusive world: World, value: any): T)?
}

Configures an explicit component identity from a declaration.

Type parameters#

Name Description
T

Members#

namefield#

name: string?

Caller-writable. Sets the persisted identity; defaults to the derived name.

constructfield#

construct: (function(...: any): T)?

Caller-writable. Overrides the declaration's initializer for factory calls.

defaultfield#

default: (function(): T)?

Caller-writable. Overrides per-entity default initialization.

transientfield#

transient: boolean?

Caller-writable. Omits this definition's values from snapshots.

requiresfield#

requires: {ComponentInput}?

Caller-writable. Adds missing components or shared instances transitively.

savefield#

save: (function(value: T): any)?

Caller-writable. Replaces automatic encoding; pair with load or deserialize.

loadfield#

load: (function(value: any): T)?

Caller-writable. Reconstructs a saved value; excludes deserialize.

deserializefield#

deserialize: (function(exclusive world: World, value: any): T)?

Caller-writable. Reconstructs a value with the destination world; excludes load.

ComponentValueinterface#

sealed interface ComponentValue

Bounds generic helpers to records or structs deriving the component contract.

DoubleArrayinterface#

interface DoubleArray

Exposes the native, one-based packed entity ID column and its exact length.

Members#

metamethods

__lenmetamethod#

function(self: DoubleArray): integer
Arguments#
self - DoubleArray
Returns#
integer

__indexmetamethod#

function(self: DoubleArray, index: integer): integer
Arguments#
self - DoubleArray
index - integer
Returns#
integer

__newindexmetamethod#

function(self: DoubleArray, index: integer, id: integer?)
Arguments#
self - DoubleArray
index - integer
id - integer?

EdgeOptionstype#

type EdgeOptions<T> = {
    name: string?,
    construct: (function(target: integer, ...: any): T)?,
    transient: boolean?,
    requires: {ComponentInput}?,
    save: (function(value: T): any)?,
    load: (function(value: any): T)?,
    deserialize: (function(exclusive world: World, value: any): T)?,
    exclusive: boolean?,
    sparse: boolean?,
    reverseIndex: boolean?,
    cascadeDelete: boolean?
}

Configures a named payload relationship from a declaration.

Type parameters#

Name Description
T

Members#

namefield#

name: string?

Caller-writable. Sets the persisted identity; defaults to the derived name.

constructfield#

construct: (function(target: integer, ...: any): T)?

Caller-writable. Constructs an edge from its target and optional payload arguments.

transientfield#

transient: boolean?

Caller-writable. Omits this definition's edges from snapshots.

requiresfield#

requires: {ComponentInput}?

Caller-writable. Adds missing components or shared instances transitively.

savefield#

save: (function(value: T): any)?

Caller-writable. Replaces automatic encoding; pair with load or deserialize.

loadfield#

load: (function(value: any): T)?

Caller-writable. Reconstructs a saved edge; excludes deserialize.

deserializefield#

deserialize: (function(exclusive world: World, value: any): T)?

Caller-writable. Reconstructs an edge with the destination world; excludes load.

exclusivefield#

exclusive: boolean?

Caller-writable. Limits each source to one target when true.

sparsefield#

sparse: boolean?

Caller-writable. Selects entity-indexed edges instead of dense target columns.

reverseIndexfield#

reverseIndex: boolean?

Caller-writable. Maintains target-to-source lookup when true.

cascadeDeletefield#

cascadeDelete: boolean?

Caller-writable. Deletes sources with their target; requires reverseIndex and exclusive.

EntityLifecycletype#

type EntityLifecycle = OnSpawn | OnDespawn

The payload shared by entity spawn and despawn lifecycle events.

FinishSnapshotLoadrecord#

record FinishSnapshotLoad
@derive(events.event) @event(name="FinishSnapshotLoad")

Reports completion of snapshot metadata restoration.

Members#

constructors

fields

constructorconstructor#

function(prelude: SnapshotPrelude): tecs.ecs.FinishSnapshotLoad

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
prelude - SnapshotPrelude

Required. Read-only. Describes the restored snapshot.

Returns#
tecs.ecs.FinishSnapshotLoad

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").FinishSnapshotLoad(
    prelude = prelude
)

preludefield#

prelude: SnapshotPrelude

Read-only. Describes the restored snapshot.

FixedOverloadtype#

type FixedOverload = "drop" | "accumulate"

The policy applied when a frame exceeds its fixed-step limit.

NewRelationshiptype#

Accepts target-only options or a declaration with payload relationship options.

NewRelationship(options)#

function(options: RelationshipOptions): Relationship
Arguments#
options - RelationshipOptions
Returns#
Relationship

NewRelationship(witness, options)#

function<T>(
    witness: Type<T>,
    options: EdgeOptions<T>?
): RelationshipDefinition<T>
Type parameters#
Name Description
T
Arguments#
witness - Type<T>
options - EdgeOptions<T>?
Returns#
RelationshipDefinition<T>

OnDespawnrecord#

record OnDespawn
@derive(events.event) @event(name="OnDespawn")

Fires at the entity address and address zero immediately before removal.

Members#

constructors

instance methods

fields

constructorconstructor#

function(
    entity: integer,
    source: Archetype,
    row: integer,
    requestedDespawns: {integer}
): tecs.ecs.OnDespawn

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
entity - integer
Required.
source - Archetype
Required. Engine-owned. Identifies the entity's last committed archetype.
row - integer
Required. Engine-owned. Identifies the entity's zero-based row before removal.
requestedDespawns - {integer}
Required. Engine-owned. Collects dependent entities observers ask to despawn.
Returns#
tecs.ecs.OnDespawn

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").OnDespawn(
    entity = entity,
    source = source,
    row = row,
    requestedDespawns = requestedDespawns
)

entityfield#

entity: integer

sourcefield#

source: Archetype

Engine-owned. Identifies the entity's last committed archetype.

rowfield#

row: integer

Engine-owned. Identifies the entity's zero-based row before removal.

requestedDespawnsfield#

requestedDespawns: {integer}

Engine-owned. Collects dependent entities observers ask to despawn.

getmethod#

function<C is Component>(borrows self: OnDespawn, component: C): C.Value?

Reads one of the entity's committed components before removal.

Arguments#
borrows self - OnDespawn
component - C
Returns#
C.Value?

despawnmethod#

function(self: OnDespawn, entity: integer)

Stages another entity for despawn at the same commit barrier.

Arguments#
self - OnDespawn
entity - integer

OnSnapshotSaverecord#

record OnSnapshotSave
@derive(events.event) @event(name="OnSnapshotSave")

Allows snapshot participants to attach metadata and exclude regenerated entities.

Members#

constructors

instance methods

fields

constructorconstructor#

function(data: {[string]: any}, excluded: {Component}): tecs.ecs.OnSnapshotSave

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
data - {[string]: any}
Required. Engine-owned. Supplies save staging to event construction; use addData instead.
excluded - {Component}
Required. Engine-owned. Supplies exclusion staging to event construction; use exclude instead.
Returns#
tecs.ecs.OnSnapshotSave

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").OnSnapshotSave(
    data = data,
    excluded = excluded
)

datafield#

data: {[string]: any}

Engine-owned. Supplies save staging to event construction; use addData instead.

excludedfield#

excluded: {Component}

Engine-owned. Supplies exclusion staging to event construction; use exclude instead.

addDatamethod#

function(self: OnSnapshotSave, key: string, value: any)

Attaches one named detached value to the snapshot.

Arguments#
self - OnSnapshotSave
The call-scoped save event.
key - string
The unique nonempty metadata key.
value - any
The serializable metadata value.
Raises#
Type Condition
string when a key is empty or repeated.

excludemethod#

function(self: OnSnapshotSave, component: components.Selector)

Excludes every entity carrying a derived-data component.

Arguments#
self - OnSnapshotSave
The call-scoped save event.
component - components.Selector
The component whose entities must be regenerated after load.

OnSpawnrecord#

record OnSpawn
@derive(events.event) @event(name="OnSpawn")

Fires at address zero after an entity becomes committed and alive.

Members#

constructors

fields

constructorconstructor#

function(entity: integer): tecs.ecs.OnSpawn

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
entity - integer

Required.

Returns#
tecs.ecs.OnSpawn

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").OnSpawn(
    entity = entity
)

entityfield#

entity: integer

Phasetype#

type Phase = string

A frame phase.

PhaseDefinitiontype#

type PhaseDefinition = {
    name: string,
    position: integer?,
    children: {string}?
}

Declares a custom phase or ordered phase tree.

Members#

namefield#

name: string

Caller-writable. Supplies a nonempty stable system-inspection name.

positionfield#

position: integer?

Caller-writable. Selects the registry position; nil appends after existing positions.

childrenfield#

children: {string}?

Caller-writable. Lists already registered child names; nil declares a leaf.

PhaseGrouptype#

type PhaseGroup = "StartupGroup" | "FixedUpdateGroup" | "RenderGroup" | "MainGroup" | "ShutdownGroup" | "AllGroups"

An ordered predefined group of frame or lifecycle phases.

PhaseSelectiontype#

type PhaseSelection = Phase | PhaseGroup

A leaf phase or predefined group accepted by schedule controls.

Pipelineinterface#

interface Pipeline

Implements custom scheduling while the world owns entities and task scopes.

Members#

countfield#

count: integer

Read-only. Reports the registered system count.

fixedTimestepfield#

fixedTimestep: number

Read-only. Reports the fixed-step duration in seconds.

fixedMaxStepsfield#

fixedMaxSteps: integer

Read-only. Limits catch-up iterations in one frame.

fixedOverloadfield#

fixedOverload: FixedOverload

Read-only. Selects drop or accumulate for excess fixed time.

fixedAccumulatorfield#

fixedAccumulator: number

Engine-owned. Stores the fixed remainder; snapshot restore writes it.

fixedStepCountfield#

fixedStepCount: integer

Read-only. Reports completed fixed iterations.

fixedTimeDroppedfield#

fixedTimeDropped: number

Read-only. Reports abandoned fixed time in seconds.

fixedStepsDroppedfield#

fixedStepsDropped: integer

Read-only. Reports abandoned whole fixed steps.

phaseStatesfield#

phaseStates: {boolean}

Engine-owned. Stores enabled flags by registered phase position; snapshots restore it.

updatemethod#

function(
    self: Pipeline,
    dt: number,
    exclusive world: World,
    borrows scope: coroutine.Scope
)

Dispatches a frame inside the world's existing task scope.

Arguments#
self - Pipeline
The custom scheduler.
dt - number
The frame duration in seconds.
exclusive world - World
The world whose systems run.
borrows scope - coroutine.Scope
The call-scoped owner of child tasks.

runmethod#

function(
    self: Pipeline,
    phase: PhaseSelection,
    dt: number,
    exclusive world: World,
    borrows scope: coroutine.Scope
)

Dispatches one phase or phase tree inside the world's task scope.

Arguments#
self - Pipeline
The custom scheduler.
phase - PhaseSelection
The selected phase name.
dt - number
The elapsed seconds supplied to systems.
exclusive world - World
The world whose systems run.
borrows scope - coroutine.Scope
The call-scoped owner of child tasks.

addSystemmethod#

function(self: Pipeline, config: SystemConfig): string

Registers a system and returns its unique name.

Arguments#
self - Pipeline
The custom scheduler.
config - SystemConfig
The system and its ordering constraints.
Returns#
string

Returns the registered name.

removeSystemmethod#

function(self: Pipeline, name: string): boolean

Removes a named system.

Arguments#
self - Pipeline
The custom scheduler.
name - string
The registered name.
Returns#
boolean

Returns whether the system existed.

listSystemsmethod#

function(self: Pipeline): {SystemInfo}

Returns detached system inspection data.

Arguments#
self - Pipeline

The custom scheduler.

Returns#
{SystemInfo}

Returns systems in dispatch order.

setSystemEnabledmethod#

function(self: Pipeline, name: string, enabled: boolean): (boolean, string?)

Changes a registered system's enabled state.

Arguments#
self - Pipeline
The custom scheduler.
name - string
The registered name.
enabled - boolean
The desired state.
Returns#
boolean
Returns success and an optional failure reason.
string?

enablePhasemethod#

function(self: Pipeline, phase: PhaseSelection)

Enables a phase tree.

Arguments#
self - Pipeline
The custom scheduler.
phase - PhaseSelection
The selected name.

disablePhasemethod#

function(self: Pipeline, phase: PhaseSelection)

Disables a phase tree.

Arguments#
self - Pipeline
The custom scheduler.
phase - PhaseSelection
The selected name.

isPhaseEnabledmethod#

function(self: Pipeline, phase: Phase): boolean

Reports whether a leaf is enabled.

Arguments#
self - Pipeline
The custom scheduler.
phase - Phase
The selected name.
Returns#
boolean

Returns whether dispatch is enabled.

registerPhasemethod#

function(self: Pipeline, phase: PhaseDefinition)

Registers a custom phase tree and assigns any omitted position.

Arguments#
self - Pipeline
The custom scheduler.
phase - PhaseDefinition
The phase declaration.

PreviousTransform2Dstruct#

struct PreviousTransform2D ...
@derive(types.debug)

Stores the position and rotation before the current fixed step.

Members#

fields

xfield#

x: number

Engine-owned. Stores the previous horizontal position in world units.

yfield#

y: number

Engine-owned. Stores the previous vertical position in world units.

rotationfield#

rotation: number

Engine-owned. Stores the previous clockwise rotation in radians.

Queryrecord#

record Query

A reusable archetype query.

Members#

descriptorfield#

descriptor: QueryDescriptor

Read-only. Describes the normalized query; mutation after construction is unsupported.

itermethod#

function(self: Query): (IterFn, Query, Archetype?)

Iterates nonempty archetypes, in ascending group order when grouped.

Arguments#
self - Query

The query to read.

Returns#
IterFn
Returns an independent iterator yielding an archetype, count and live entity column.
Query
Archetype?

groupsmethod#

function(self: Query): (GroupsIterFn, Query, integer?)

Iterates nonempty group identifiers in ascending order.

Arguments#
self - Query

The query to read.

Returns#
GroupsIterFn
Returns an independent iterator, empty for ungrouped queries.
Query
integer?

groupmethod#

function(self: Query, groupId: integer): (GroupIterFn, GroupState, Archetype?)

Iterates nonempty archetypes in one group.

Arguments#
self - Query
The query to read.
groupId - integer
The integer group identifier.
Returns#
GroupIterFn
Returns an independent iterator yielding an archetype, count and live entity column.
GroupState
Archetype?

getGroupmethod#

function(self: Query, candidate: Archetype): integer?

Returns an archetype's assigned group.

Arguments#
self - Query
The query to read.
candidate - Archetype
The archetype to inspect.
Returns#
integer?

Returns nil when unmatched or ungrouped.

getGroupCountmethod#

function(self: Query, groupId: integer): integer

Counts entities in one group.

Arguments#
self - Query
The query to read.
groupId - integer
The integer group identifier.
Returns#
integer

Returns zero when the group is absent.

countmethod#

function(self: Query): integer

Counts all currently matching entities.

Arguments#
self - Query

The query to read.

Returns#
integer

Returns the committed entity count.

QueryDescriptortype#

type QueryDescriptor = {
    name: string?,
    type: ("logic" | "render")?,
    include: const{components.Selector}?,
    includeAny: const{components.Selector}?,
    exclude: const{components.Selector}?,
    onEntitiesAdded: MembershipCallback?,
    onEntitiesRemoved: MembershipCallback?,
    temp: boolean?,
    groupBy: (function(candidate: Archetype): integer)?
}

Membership constraints, grouping and notifications for a reusable query.

Members#

namefield#

name: string?

Caller-writable. Names this query for inspection.

typefield#

type: ("logic" | "render")?

Caller-writable. Excludes Paused for logic queries; nil behaves like render.

includefield#

include: const{components.Selector}?

Caller-writable. Requires all listed components and overrides their automatic exclusions.

includeAnyfield#

includeAny: const{components.Selector}?

Caller-writable. Requires at least one listed component; an empty list adds no constraint.

excludefield#

exclude: const{components.Selector}?

Caller-writable. Rejects every listed component.

onEntitiesAddedfield#

onEntitiesAdded: MembershipCallback?

Caller-writable. Receives entering rows after publication, including initial members.

onEntitiesRemovedfield#

onEntitiesRemoved: MembershipCallback?

Caller-writable. Receives departing rows while their old values remain readable.

tempfield#

temp: boolean?

Caller-writable. Retains only initially matching archetypes, with live rows, and forbids callbacks.

groupByfield#

groupBy: (function(candidate: Archetype): integer)?

Caller-writable. Assigns each matching archetype an integer group once.

Relationshiprecord#

record Relationship is Component

A target-only entity relationship with selectable cardinality and storage.

Members#

constructorconstructor#

function(
    componentId: integer,
    componentName: string,
    storageType: string,
    transient: boolean,
    exclusive: boolean,
    reverseIndex: boolean,
    cascadeDelete: boolean,
    sparse: boolean
): tecs.ecs.Relationship

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
componentId - integer
Required.
componentName - string
Required.
storageType - string
Required.
transient - boolean
Required.
exclusive - boolean
Required.
reverseIndex - boolean
Required.
cascadeDelete - boolean
Required.
sparse - boolean
Required. Read-only. Selects entity-indexed edge storage; false selects target-specific dense columns.
Returns#
tecs.ecs.Relationship

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").Relationship(
    componentId = componentId,
    componentName = componentName,
    storageType = storageType,
    transient = transient,
    exclusive = exclusive,
    reverseIndex = reverseIndex,
    cascadeDelete = cascadeDelete,
    sparse = sparse
)

Valuefield#

Value: associatedDecl

componentIdfield#

componentId: integer

componentNamefield#

componentName: string

storageTypefield#

storageType: string

transientfield#

transient: boolean

exclusivefield#

exclusive: boolean

reverseIndexfield#

reverseIndex: boolean

cascadeDeletefield#

cascadeDelete: boolean

sparsefield#

sparse: boolean

Read-only. Selects entity-indexed edge storage; false selects target-specific dense columns.

__callmetamethod#

function(self, target: integer): RelationshipInstance
Arguments#
? - self
target - integer
Returns#
RelationshipInstance

targetingmethod#

function(self: Relationship, target: integer): Relationship

Returns a component matching one target of this dense relationship.

Arguments#
self - Relationship
The relationship definition.
target - integer
The packed target entity identifier.
Returns#
Relationship

Returns a stable target-specific component definition.

Raises#
Type Condition
string when the relationship uses sparse storage or the target is invalid.

RelationshipDefinitioninterface#

interface RelationshipDefinition<T> is Component

A payload relationship whose target selector retains the physical column type.

Type parameters#

Name Description
T

Members#

implements

static methods

instance methods

metamethods

fields

Valuefield#

Value: associatedDecl

Columnfield#

Column: associatedDecl

constructmethod#

function(...: any): T
Arguments#
... - any
Returns#
T

defaultFactorymethod#

function(): T
Returns#
T

snapshotSavemethod#

function(value: T): any
Arguments#
value - T
Returns#
any

snapshotLoadmethod#

function(value: any, exclusive world: any): T
Arguments#
value - any
exclusive world - any
Returns#
T

__callmetamethod#

function(
    self,
    ...: any
): tecs.gfx.models.BoundsInput<T, RelationshipDefinition<T>>
Arguments#
? - self
... - any
Returns#
tecs.gfx.models.BoundsInput<T, RelationshipDefinition<T>>

targetingmethod#

function(
    self: RelationshipDefinition<T>,
    target: integer
): ComponentDefinition<T>
Arguments#
self - RelationshipDefinition<T>
target - integer
Returns#
ComponentDefinition<T>

RelationshipOptionstype#

type RelationshipOptions = {
    name: string,
    exclusive: boolean?,
    sparse: boolean?,
    reverseIndex: boolean?,
    cascadeDelete: boolean?,
    requires: {ComponentInput}?,
    transient: boolean?
}

Construction and storage options for target-only relationships.

Members#

namefield#

name: string

Caller-writable. Sets the stable process-wide relationship name.

exclusivefield#

exclusive: boolean?

Caller-writable. Limits each source to one target when true; defaults to false.

sparsefield#

sparse: boolean?

Caller-writable. Uses entity-indexed storage instead of target-specific archetypes when true.

reverseIndexfield#

reverseIndex: boolean?

Caller-writable. Maintains target-to-source lookup when true.

cascadeDeletefield#

cascadeDelete: boolean?

Caller-writable. Deletes sources with their target; requires exclusive and reverseIndex.

requiresfield#

requires: {ComponentInput}?

Caller-writable. Adds missing definitions or shared instance values when an edge first adds this relationship. Tecs copies the list at registration.

transientfield#

transient: boolean?

Caller-writable. Omits this relationship from snapshots when true.

RelationshipPayloadinterface#

sealed interface RelationshipPayload is ComponentValue

Bounds generic helpers to target-bearing declarations deriving the relationship contract.

Members#

implements

RelationshipValuerecord#

record RelationshipValue

A target-only relationship edge value.

Members#

constructors

fields

constructorconstructor#

function(target: integer): tecs.ecs.RelationshipValue

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
target - integer

Required. Read-only. Names the target; replace the edge through world:set to retarget it.

Returns#
tecs.ecs.RelationshipValue

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").RelationshipValue(
    target = target
)

targetfield#

target: integer

Read-only. Names the target; replace the edge through world:set to retarget it.

RelativeTransform2Dstruct#

struct RelativeTransform2D ...
@derive(types.debug)

Offsets an entity from the transform of the parent it names with ChildOf.

Members#

xfield#

x: number

Caller-writable. Sets the horizontal offset from the parent, in the parent's rotated and scaled space.

yfield#

y: number

Caller-writable. Sets the vertical offset from the parent, in the parent's rotated and scaled space.

zfield#

z: number

Caller-writable. Sets the depth offset added to the parent's depth.

rotationfield#

rotation: number

Caller-writable. Sets the clockwise rotation in radians added to the parent's rotation.

scaleXfield#

scaleX: number

Caller-writable. Sets the horizontal scale multiplied by the parent's.

scaleYfield#

scaleY: number

Caller-writable. Sets the vertical scale multiplied by the parent's.

originXfield#

originX: number

Caller-writable. Sets the horizontal origin as a fraction of the entity's width, where zero is the left edge and one the right. The builtin composition carries this value and does not read it, because nothing in the transform knows the entity's size; a layout module that does read it is what gives it meaning.

originYfield#

originY: number

Caller-writable. Sets the vertical origin as a fraction of the entity's height, where zero is the top edge and one the bottom. The builtin composition carries this value and does not read it.

RunIftype#

type RunIf = function(dt: number, exclusive world: World, systemName: string): boolean

A predicate receiving the phase delta, world and registered system name.

Arguments#

dt - number
exclusive world - World
systemName - string

Returns#

boolean

ScalarComponentrecord#

record ScalarComponent<T> is Component

A primitive-valued component definition.

Type parameters#

Name Description
T

Members#

constructorconstructor#

function(
    componentId: integer,
    componentName: string,
    storageType: string,
    transient: boolean,
    scalarKind: "number" | "boolean" | "string",
    scalarDefault: T
): tecs.ecs.ScalarComponent<T>

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
componentId - integer
Required.
componentName - string
Required.
storageType - string
Required.
transient - boolean
Required.
scalarKind - "number" | "boolean" | "string"
Required.
scalarDefault - T
Required.
Returns#
tecs.ecs.ScalarComponent<T>

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").ScalarComponent(
    componentId = componentId,
    componentName = componentName,
    storageType = storageType,
    transient = transient,
    scalarKind = scalarKind,
    scalarDefault = scalarDefault
)

Valuefield#

Value: associatedDecl

componentIdfield#

componentId: integer

componentNamefield#

componentName: string

storageTypefield#

storageType: string

transientfield#

transient: boolean

scalarKindfield#

scalarKind: "number" | "boolean" | "string"

scalarDefaultfield#

scalarDefault: T

__callmetamethod#

function(self, value: T): ScalarInstance<T>
Arguments#
? - self
value - T
Returns#
ScalarInstance<T>

ScalarComponentOptionstype#

type ScalarComponentOptions = NumberComponentOptions | BooleanComponentOptions | StringComponentOptions

Options accepted by the kind-correlated scalar component factory.

Snapshotrecord#

record Snapshot

A detached, format-neutral world snapshot.

Members#

constructorconstructor#

function(version: integer, nextEntityId: integer, entityCount: integer, archetypeCount: integer, componentTable: {
    SnapshotComponentEntry
}, archetypes: {
    SnapshotArchetype
}, data: {
    SnapshotDataEntry
}, states: {string}, format: ("binary" | "table")?, bytes: string?, pipeline: {
    fixedAccumulator: number,
    phaseStates: {boolean},
    disabledPhases: {[string]: boolean}
}?): tecs.ecs.Snapshot

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
version - integer
Required.
nextEntityId - integer
Required.
entityCount - integer
Required.
archetypeCount - integer
Required.
componentTable - {SnapshotComponentEntry}
Required.
archetypes - {SnapshotArchetype}
Required.
data - {SnapshotDataEntry}
Required.
states - {string}
Required.
format - ("binary" | "table")?
Optional. Defaults to nil. Read-only. Identifies binary output when a native buffer was requested.
bytes - string?
Optional. Defaults to nil. Read-only. Holds the encoded binary snapshot when format is "binary". The string is the caller's to keep, write to a file or pass to loadSnapshot.

pipeline - { fixedAccumulator: number, phaseStates: {boolean}, disabledPhases: {[string]: boolean} }? : Optional. Defaults to nil. Read-only. Preserves fixed-step remainder and disabled phase names in table output.

Returns#
tecs.ecs.Snapshot

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").Snapshot(
    version = version,
    nextEntityId = nextEntityId,
    entityCount = entityCount,
    archetypeCount = archetypeCount,
    componentTable = componentTable,
    archetypes = archetypes,
    data = data,
    states = states
)

versionfield#

version: integer

nextEntityIdfield#

nextEntityId: integer

entityCountfield#

entityCount: integer

archetypeCountfield#

archetypeCount: integer

componentTablefield#

componentTable: {SnapshotComponentEntry}

archetypesfield#

archetypes: {SnapshotArchetype}

datafield#

data: {SnapshotDataEntry}

statesfield#

states: {string}

formatfield#

format: ("binary" | "table")?

Read-only. Identifies binary output when a native buffer was requested.

bytesfield#

bytes: string?

Read-only. Holds the encoded binary snapshot when format is "binary". The string is the caller's to keep, write to a file or pass to loadSnapshot.

pipelinefield#

pipeline: {
    fixedAccumulator: number,
    phaseStates: {boolean},
    disabledPhases: {[string]: boolean}
}?

Read-only. Preserves fixed-step remainder and disabled phase names in table output.

SnapshotHandlertype#

type SnapshotHandler = {
    name: string,
    save: (function(exclusive world: World): any)?,
    load: (function(exclusive world: World, value: any): nil)?,
    finish: (function(exclusive world: World, prelude: SnapshotPrelude): nil)?
}

A named custom snapshot participant.

Members#

namefield#

name: string

savefield#

save: (function(exclusive world: World): any)?

loadfield#

load: (function(exclusive world: World, value: any): nil)?

finishfield#

finish: (function(exclusive world: World, prelude: SnapshotPrelude): nil)?

SnapshotOptionstype#

type SnapshotOptions = {
    customData: {[string]: any}?,
    filterQuery: QueryDescriptor?,
    layers: {integer}?,
    format: ("binary" | "table")?,
    path: string?
}

Options for adding custom snapshot data.

Members#

customDatafield#

customData: {[string]: any}?

Caller-writable. Attaches unique named custom data.

filterQueryfield#

filterQuery: QueryDescriptor?

Caller-writable. Selects entities without automatic Disabled or Paused exclusions.

layersfield#

layers: {integer}?

Caller-writable. Selects draw layers from zero through 31; entities without Transform2D always pass.

formatfield#

format: ("binary" | "table")?

Caller-writable. Chooses binary framing or a detached table; nil retains table output.

pathfield#

path: string?

Caller-writable. Writes binary output to this file as well as returning it.

SnapshotPreluderecord#

record SnapshotPrelude

Metadata returned by a snapshot load.

Members#

constructorconstructor#

function(
    version: integer,
    nextEntityId: integer,
    entityCount: integer,
    archetypeCount: integer,
    componentTable: {SnapshotComponentEntry}
): tecs.ecs.SnapshotPrelude

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
version - integer
Required. Read-only. Reports the ECS framing version, independently of game data versions.
nextEntityId - integer
Required. Read-only. Reports the next fresh entity slot after restoration.
entityCount - integer
Required. Read-only. Reports the number of saved entities.
archetypeCount - integer
Required. Read-only. Reports the number of saved archetype frames.
componentTable - {SnapshotComponentEntry}
Required. Read-only. Lists the saved component names and native layouts in frame-index order.
Returns#
tecs.ecs.SnapshotPrelude

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").SnapshotPrelude(
    version = version,
    nextEntityId = nextEntityId,
    entityCount = entityCount,
    archetypeCount = archetypeCount,
    componentTable = componentTable
)

versionfield#

version: integer

Read-only. Reports the ECS framing version, independently of game data versions.

nextEntityIdfield#

nextEntityId: integer

Read-only. Reports the next fresh entity slot after restoration.

entityCountfield#

entityCount: integer

Read-only. Reports the number of saved entities.

archetypeCountfield#

archetypeCount: integer

Read-only. Reports the number of saved archetype frames.

componentTablefield#

componentTable: {SnapshotComponentEntry}

Read-only. Lists the saved component names and native layouts in frame-index order.

StartSnapshotLoadrecord#

record StartSnapshotLoad
@derive(events.event) @event(name="StartSnapshotLoad")

Allows snapshot participants to subscribe to metadata during a load.

Members#

constructors

instance methods

fields

constructorconstructor#

function(
    prelude: SnapshotPrelude,
    handlers: {[string]: {function(value: any)}}
): tecs.ecs.StartSnapshotLoad

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
prelude - SnapshotPrelude
Required. Read-only. Describes the snapshot being restored.
handlers - {[string]: {function(value: any)}}
Required. Engine-owned. Supplies dispatch staging to event construction; use onData instead.
Returns#
tecs.ecs.StartSnapshotLoad

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").StartSnapshotLoad(
    prelude = prelude,
    handlers = handlers
)

preludefield#

prelude: SnapshotPrelude

Read-only. Describes the snapshot being restored.

handlersfield#

handlers: {[string]: {function(value: any)}}

Engine-owned. Supplies dispatch staging to event construction; use onData instead.

onDatamethod#

function(self: StartSnapshotLoad, key: string, callback: function(value: any))

Subscribes to one custom-data key for this load only.

Arguments#
self - StartSnapshotLoad
The call-scoped load event.
key - string
The nonempty metadata key.
callback - function(value: any)
The callback; multiple listeners receive the same key in registration order.
Raises#
Type Condition
string when the key is empty.

StateBlurrecord#

record StateBlur
@derive(events.event) @event(name="StateBlur")

Fires after the current state loses focus.

Members#

constructors

fields

constructorconstructor#

function(state: string, pushed: string): tecs.ecs.StateBlur

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
state - string
Required.
pushed - string
Required.
Returns#
tecs.ecs.StateBlur

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").StateBlur(
    state = state,
    pushed = pushed
)

statefield#

state: string

pushedfield#

pushed: string

StateBlurChangerecord#

record StateBlurChange
@derive(events.event) @event(name="StateBlur")

The payload emitted when a state loses focus.

Members#

constructors

fields

constructorconstructor#

function(state: string, pushed: string): tecs.ecs.StateBlurChange

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
state - string
Required.
pushed - string
Required.
Returns#
tecs.ecs.StateBlurChange

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").StateBlurChange(
    state = state,
    pushed = pushed
)

statefield#

state: string

pushedfield#

pushed: string

StateChangetype#

type StateChange = StateEnter | StateExit

The payload emitted when a state enters or exits.

StateEnterrecord#

record StateEnter
@derive(events.event) @event(name="StateEnter")

Fires after a state becomes active.

Members#

constructors

fields

constructorconstructor#

function(state: string): tecs.ecs.StateEnter

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
state - string

Required.

Returns#
tecs.ecs.StateEnter

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").StateEnter(
    state = state
)

statefield#

state: string

StateExitrecord#

record StateExit
@derive(events.event) @event(name="StateExit")

Fires before a state leaves the stack.

Members#

constructors

fields

constructorconstructor#

function(state: string): tecs.ecs.StateExit

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
state - string

Required.

Returns#
tecs.ecs.StateExit

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").StateExit(
    state = state
)

statefield#

state: string

StateFocusrecord#

record StateFocus
@derive(events.event) @event(name="StateFocus")

Fires after an uncovered state regains focus.

Members#

constructors

fields

constructorconstructor#

function(state: string, popped: string): tecs.ecs.StateFocus

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
state - string
Required.
popped - string
Required.
Returns#
tecs.ecs.StateFocus

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").StateFocus(
    state = state,
    popped = popped
)

statefield#

state: string

poppedfield#

popped: string

StateFocusChangerecord#

record StateFocusChange
@derive(events.event) @event(name="StateFocus")

The payload emitted when a state regains focus.

Members#

constructors

fields

constructorconstructor#

function(state: string, popped: string): tecs.ecs.StateFocusChange

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
state - string
Required.
popped - string
Required.
Returns#
tecs.ecs.StateFocusChange

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").StateFocusChange(
    state = state,
    popped = popped
)

statefield#

state: string

poppedfield#

popped: string

StatePolicytype#

type StatePolicy = {
    onBlur: StatePolicyOperation?,
    onFocus: StatePolicyOperation?,
    onEnter: StatePolicyOperation?,
    onExit: StatePolicyOperation?
}

Policy hooks for one world state.

Members#

onBlurfield#

onBlur: StatePolicyOperation?

onFocusfield#

onFocus: StatePolicyOperation?

onEnterfield#

onEnter: StatePolicyOperation?

onExitfield#

onExit: StatePolicyOperation?

Systemtype#

type System = function(dt: number, exclusive world: World, borrows scope: coroutine.Scope)

A system body receiving elapsed time, its world, and the update task scope.

Arguments#

dt - number
exclusive world - World
borrows scope - coroutine.Scope

SystemConfigtype#

type SystemConfig = {
    name: string?,
    phase: Phase,
    run: System,
    runIf: RunIf?,
    before: {string}?,
    after: {string}?,
    commitBefore: boolean?,
    commitAfter: boolean?
}

Registration options for a frame system.

Members#

namefield#

name: string?

Caller-writable. Names the system uniquely; nil requests an engine-owned name.

phasefield#

phase: Phase

Caller-writable. Selects the leaf phase that dispatches the system.

runfield#

run: System

Caller-writable. Receives the phase delta, world and borrowed task scope.

runIffield#

runIf: RunIf?

Caller-writable. Gates each dispatch; a disabled system does not evaluate it.

beforefield#

before: {string}?

Caller-writable. Names systems that must run later in this phase; missing and cross-phase names contribute no edge. The world copies the list.

afterfield#

after: {string}?

Caller-writable. Names systems that must run earlier in this phase; missing and cross-phase names contribute no edge. The world copies the list.

commitBeforefield#

commitBefore: boolean?

Caller-writable. Publishes staged changes before evaluating runIf.

commitAfterfield#

commitAfter: boolean?

Caller-writable. Publishes staged changes after dispatch, even when runIf is false.

SystemInfotype#

type SystemInfo = {
    name: string,
    phase: Phase,
    position: integer,
    enabled: boolean,
    hasRunIf: boolean
}

One registered system as reported in execution order.

Members#

namefield#

name: string

Read-only. Names the registered system.

phasefield#

phase: Phase

Read-only. Names its dispatch phase.

positionfield#

position: integer

Read-only. Reports its position in the inspected schedule.

enabledfield#

enabled: boolean

Read-only. Reports whether the scheduler permits dispatch.

hasRunIffield#

hasRunIf: boolean

Read-only. Reports whether dispatch has an additional predicate.

TagComponentOptionstype#

type TagComponentOptions = {
    name: string,
    transient: boolean?,
    requires: {ComponentInput}?
}

Options for a marker component with no per-entity value.

Members#

namefield#

name: string

transientfield#

transient: boolean?

requiresfield#

requires: {ComponentInput}?

Caller-writable. Adds missing definitions or shared instance values, including transitive requirements. Tecs copies the list at registration.

Transform2Dstruct#

struct Transform2D ...
@derive(types.debug)

Places an entity in the two-dimensional world.

Members#

xfield#

x: number

Caller-writable. Sets the horizontal position in world units.

yfield#

y: number

Caller-writable. Sets the vertical position in world units.

zfield#

z: number

Caller-writable. Sets depth within the selected layer.

layerfield#

layer: integer

Caller-writable. Selects the integer draw layer.

rotationfield#

rotation: number

Caller-writable. Sets clockwise rotation in radians.

scaleXfield#

scaleX: number

Caller-writable. Sets horizontal scale in world units.

scaleYfield#

scaleY: number

Caller-writable. Sets vertical scale in world units.

Transform3Dstruct#

struct Transform3D ...
@derive(types.debug)

Places an entity in a right-handed 3D world using a quaternion and per-axis scale.

Members#

xfield#

x: number

yfield#

y: number

zfield#

z: number

rotationXfield#

rotationX: number

rotationYfield#

rotationY: number

rotationZfield#

rotationZ: number

rotationWfield#

rotationW: number

scaleXfield#

scaleX: number

scaleYfield#

scaleY: number

scaleZfield#

scaleZ: number

TTLstruct#

struct TTL ...
@derive(types.debug)

Counts down an entity's remaining lifetime.

Members#

instance methods

fields

startingTimefield#

startingTime: number

Caller-writable. Sets the lifetime the entity started with, in seconds, which is what percentComplete measures against. Raising remaining past this value leaves percentComplete negative, so refresh both when a pickup extends a timer.

remainingfield#

remaining: number

Caller-writable. Sets the seconds of fixed time left before the entity is despawned. Writing a larger value refreshes the timer.

percentCompletemethod#

function(self: TTL): number

Returns elapsed lifetime as a fraction from zero at spawn to one at expiry.

A fresh TTL answers zero and an expired one answers one, so a fade or a shrink can drive straight off it. A value restored from a snapshot whose startingTime is zero also answers one, because nothing distinguishes it from having run out.

Arguments#
self - TTL

the lifetime to measure

Returns#
number

the completed fraction, clamped to the range zero through one

Worldrecord#

record World

A Tecs world.

Members#

liveCountfield#

liveCount: integer

archetypeCountfield#

archetypeCount: integer

systemCountfield#

systemCount: integer

observersfield#

observers: nuppevents.MessageBus<integer>

Observer registrations by address and event; observers:count() is how many are live.

resourcesfield#

resources: Store

spawnmethod#

function(exclusive self: World, ...: ComponentInput): integer
Arguments#
exclusive self - World
... - ComponentInput
Returns#
integer

spawnAtmethod#

function(exclusive self: World, id: integer, ...: ComponentInput)
Arguments#
exclusive self - World
id - integer
... - ComponentInput

batchSpawnmethod#

function(
    exclusive self: World,
    count: integer,
    inputs: {ComponentInput},
    callback: BatchCallback?
): (integer?, {integer}?)

Reserves a batch sharing one signature and initializes its rows at the next barrier.

Arguments#
exclusive self - World
The world to modify.
count - integer
The positive number of entities to reserve.
inputs - {ComponentInput}
The component definitions or values, including required defaults.
callback - BatchCallback?
The optional initializer, called before membership and spawn events.
Returns#
integer?
Returns a first packed id and nil for a contiguous range, or nil and an explicit id list when slots or generations are non-contiguous.
{integer}?
Raises#
Type Condition
string for invalid count, exhausted capacity, bare relationships or EntityKey.

batchSpawnAtmethod#

function(
    exclusive self: World,
    ids: {integer},
    inputs: {ComponentInput},
    callback: BatchCallback?
)

Reserves supplied packed identities in order for a deferred batch spawn.

Arguments#
exclusive self - World
The world to modify.
ids - {integer}
The identities to restore; an empty list does nothing.
inputs - {ComponentInput}
The shared component signature and initial values.
callback - BatchCallback?
The optional row initializer at publication.
Raises#
Type Condition
string before reserving any id if one is invalid, duplicated or occupied, or the signature contains EntityKey or a bare relationship.

batchSpawnAtRawmethod#

function(
    exclusive self: World,
    ids: number[?],
    count: integer,
    inputs: {ComponentInput},
    callback: BatchCallback?
)

Reserves packed identities directly from a zero-based native double array.

Arguments#
exclusive self - World
The world to modify.
ids - number[?]
The borrowed array, retained until publication. Do not change its selected prefix before the barrier.
count - integer
The number of identities in the prefix; zero does nothing.
inputs - {ComponentInput}
The shared signature. Unlike ordinary batch spawns, this restoration path permits EntityKey, initialized before key registration.
callback - BatchCallback?
The optional initializer, called before indexes and observers.
Raises#
Type Condition
string before reservation for an invalid count, identity, duplicate, occupied slot, or bare relationship.

batchSetmethod#

function(
    exclusive self: World,
    selection: Query,
    input: ComponentInput,
    callback: BatchCallback?
)

Stages a value or deferred column writer for currently matching entities.

Arguments#
exclusive self - World
The world owning the query.
selection - Query
The reusable query; membership is captured at this call.
input - ComponentInput
The component value, or definition when supplying a callback.
callback - BatchCallback?
The optional writer, called for each contiguous affected range.
Raises#
Type Condition
string for a foreign query, EntityKey, or callback mode with an instance or relationship. Relationship values support constant mode.

batchRemovemethod#

function(exclusive self: World, selection: Query, input: ComponentInput)

Stages component removal for the query's current committed members.

Arguments#
exclusive self - World
The world owning the query.
selection - Query
The reusable query to capture now.
input - ComponentInput
The component definition or a relationship value selecting one target.
Raises#
Type Condition
string when the query belongs to another world.

batchDespawnmethod#

function(exclusive self: World, selection: Query)

Stages normal teardown, events and cascading for currently matching entities.

Arguments#
exclusive self - World
The world owning the query.
selection - Query
The reusable query to capture now.
Raises#
Type Condition
string when the query belongs to another world.

forEachArchetypemethod#

function(borrows self: World, callback: function(candidate: Archetype))

Visits every archetype, including empty and disabled ones, in registry order.

Arguments#
borrows self - World
The world to inspect.
callback - function(candidate: Archetype)
The callback; it must not commit or compact during this traversal.

findArchetypesmethod#

function(
    borrows self: World,
    component: components.Selector
): function(): (Archetype?, integer?, DoubleArray?)

Iterates registered archetypes containing a component, including empty ones.

Arguments#
borrows self - World
The world to inspect.
component - components.Selector
The component used to select the index.
Returns#
function(): (Archetype?, integer?, DoubleArray?)

Returns an iterator over the live component index.

dirtyArchetypesmethod#

function(borrows self: World): function(): Archetype?

Captures archetypes with dirty components in registry order.

Arguments#
borrows self - World

The world to inspect.

Returns#
function(): Archetype?

Returns an independent iterator, including empty dirty archetypes.

compactmethod#

function(exclusive self: World): (integer, integer)

Prunes empty dead-target archetypes and rebuilds storage that has lost rows.

Arguments#
exclusive self - World

A quiet world with no pending mutations or active dispatch.

Returns#
integer
Returns the number of archetypes pruned and surviving stores rebuilt.
integer
Raises#
Type Condition
string during dispatch, publication, or with uncommitted work.

isAlivemethod#

function(borrows self: World, id: integer): boolean
Arguments#
borrows self - World
id - integer
Returns#
boolean

hasmethod#

function(
    borrows self: World,
    id: integer,
    component: components.Selector
): boolean
Arguments#
borrows self - World
id - integer
component - components.Selector
Returns#
boolean

byKeymethod#

function(borrows self: World, key: string): integer?
Arguments#
borrows self - World
key - string
Returns#
integer?

requireKeymethod#

function(borrows self: World, key: string): integer
Arguments#
borrows self - World
key - string
Returns#
integer

getmethod#

get(self, id, component)#
function<C is Component>(
    borrows self: World,
    id: integer,
    component: C
): C.Value?
Type parameters#
Name Description
C
Arguments#
borrows self - World
id - integer
component - C
Returns#
C.Value?
get(self, id, component)#
function<T is ComponentValue>(
    borrows self: World,
    id: integer,
    component: Type<T>
): T?
Type parameters#
Name Description
T
Arguments#
borrows self - World
id - integer
component - Type<T>
Returns#
T?

getMutmethod#

getMut(self, id, component)#
function<C is Component>(
    exclusive self: World,
    id: integer,
    component: C
): C.Value?
Type parameters#
Name Description
C
Arguments#
exclusive self - World
id - integer
component - C
Returns#
C.Value?
getMut(self, id, component)#
function<T is ComponentValue>(
    exclusive self: World,
    id: integer,
    component: Type<T>
): T?
Type parameters#
Name Description
T
Arguments#
exclusive self - World
id - integer
component - Type<T>
Returns#
T?

markComponentDirtymethod#

function(exclusive self: World, id: integer, component: components.Selector)
Arguments#
exclusive self - World
id - integer
component - components.Selector

relationshipSourcesmethod#

function(
    borrows self: World,
    relationship: components.Selector,
    target: integer
): {integer}
Arguments#
borrows self - World
relationship - components.Selector
target - integer
Returns#
{integer}

forEachRelationshipmethod#

Iterates a source entity's edges in target order.

forEachRelationship(self, id, relationship, callback)#
function<C is Component>(
    borrows self: World,
    id: integer,
    relationship: C,
    callback: function(value: C.Value)
)
Type parameters#
Name Description
C
Arguments#
borrows self - World
The world to inspect.
id - integer
The committed source identifier.
relationship - C
The relationship definition or target-specific component.
callback - function(value: C.Value)
The callback receiving each live edge value.
forEachRelationship(self, id, relationship, callback)#
function<T is RelationshipPayload>(
    borrows self: World,
    id: integer,
    relationship: Type<T>,
    callback: function(value: T)
)
Type parameters#
Name Description
T
Arguments#
borrows self - World
The world to inspect.
id - integer
The committed source identifier.
relationship - Type<T>
The relationship definition or target-specific component.
callback - function(value: T)
The callback receiving each live edge value.

getFirstRelationshipmethod#

Returns the first edge in target order.

getFirstRelationship(self, id, relationship)#
function<C is Component>(
    borrows self: World,
    id: integer,
    relationship: C
): C.Value?
Type parameters#
Name Description
C
Arguments#
borrows self - World
The world to inspect.
id - integer
The committed source identifier.
relationship - C
The relationship to inspect.
Returns#
C.Value?

Returns nil when the source or edge is absent.

getFirstRelationship(self, id, relationship)#
function<T is RelationshipPayload>(
    borrows self: World,
    id: integer,
    relationship: Type<T>
): T?
Type parameters#
Name Description
T
Arguments#
borrows self - World
The world to inspect.
id - integer
The committed source identifier.
relationship - Type<T>
The relationship to inspect.
Returns#
T?

Returns nil when the source or edge is absent.

targetsmethod#

function<T>(
    borrows self: World,
    target: integer,
    relationship: components.Selector,
    callback: function(source: integer, context: T),
    context: T
)

Visits sources targeting an entity in ascending identifier order.

Type parameters#
Name Description
T
Arguments#
borrows self - World
The world to inspect.
target - integer
The target entity identifier.
relationship - components.Selector
The reverse-indexed relationship.
callback - function(source: integer, context: T)
The callback receiving each source and the caller's context.
context - T
The caller-owned callback context.
Raises#
Type Condition
string when the relationship has no reverse index.

traversemethod#

function(
    borrows self: World,
    root: integer,
    relationship: components.Selector
): function(): (integer?, integer?)

Traverses descendants depth first, visiting each identifier at most once.

Arguments#
borrows self - World
The world to inspect.
root - integer
The excluded root identifier.
relationship - components.Selector
The reverse-indexed relationship.
Returns#
function(): (integer?, integer?)

Returns an iterator yielding depth and entity; direct children have depth zero.

Raises#
Type Condition
string when the relationship has no reverse index.

walkUpmethod#

function<T>(
    borrows self: World,
    id: integer,
    relationship: components.Selector,
    callback: function(ancestor: integer, depth: integer, context: T): boolean?,
    context: T,
    maxDepth: integer?
)

Walks the first outgoing edge at each level, in target order.

Type parameters#
Name Description
T
Arguments#
borrows self - World
The world to inspect.
id - integer
The excluded starting entity.
relationship - components.Selector
The relationship to follow.
callback - function(ancestor: integer, depth: integer, context: T): boolean?
The callback receiving ancestor, depth starting at one, and context; false stops traversal.
context - T
The caller-owned callback context.
maxDepth - integer?
The positive depth limit, defaulting to 100.
Raises#
Type Condition
string on a cycle or when the depth limit is exceeded.

newQuerymethod#

function(exclusive self: World, descriptor: QueryDescriptor?): Query

Creates a query over committed entities, excluding Disabled by default.

Arguments#
exclusive self - World
The world that owns the query.
descriptor - QueryDescriptor?
The constraints and callbacks; nil matches enabled entities.
Returns#
Query

Returns a persistent query unless temp is true.

Raises#
Type Condition
string for an invalid query type or temporary membership callbacks.

setmethod#

function(
    exclusive self: World,
    id: integer,
    input: ComponentInput,
    value: any?
)
Arguments#
exclusive self - World
id - integer
input - ComponentInput
value - any?

removemethod#

function(exclusive self: World, id: integer, input: ComponentInput)
Arguments#
exclusive self - World
id - integer
input - ComponentInput

despawnmethod#

function(exclusive self: World, id: integer)
Arguments#
exclusive self - World
id - integer

commitmethod#

function(exclusive self: World)

Publishes staged mutations synchronously, including work staged by observers. Reentrant calls during publication join the active drain.

Arguments#
exclusive self - World

The world to publish; callers must leave query iteration first.

Raises#
Type Condition
string when a publication callback raises.

enqueueCommitmethod#

function(exclusive self: World)

Requests publication after the current system and its predicate return. Repeated requests coalesce, including across suspension. Outside a system this publishes synchronously; publication callbacks join the active drain. A failed system cancels the request without publishing its staged work.

Arguments#
exclusive self - World

The world whose pending mutations need a publication barrier.

Raises#
Type Condition
string when a synchronous publication callback raises.

randomStreammethod#

function(exclusive self: World, name: string): math.Xoshiro128

Returns this world's stable named Nupp random generator. Stream names and the world seed determine independent sequences. The world snapshots generators automatically and restores captured objects in place.

Arguments#
exclusive self - World
The world that owns the generator and its snapshot state.
name - string
The non-empty stream name, preferably namespaced for its consumer.
Returns#
math.Xoshiro128

Returns the same mutable generator for each call with this name.

Raises#
Type Condition
string when the name is empty.

seedRandommethod#

function(exclusive self: World, seed: integer)

Restarts every named random stream without replacing captured generators. Streams created later derive their seeds from this seed too.

Arguments#
exclusive self - World
The world whose random sequences restart.
seed - integer
The finite integer seed, interpreted as a 32-bit word.
Raises#
Type Condition
string when the seed is not a finite integer.

clearEntitiesmethod#

function(exclusive self: World)

Clears entity data and pending batches while preserving systems, queries and resources.

Arguments#
exclusive self - World

The world to reset; reserved identities are invalidated too.

Raises#
Type Condition
string during publication. Use staged despawn from callbacks instead.

addSystemmethod#

function(exclusive self: World, config: SystemConfig): string

Registers a system for the next external dispatch, copying its constraints.

Arguments#
exclusive self - World
The world to modify.
config - SystemConfig
The phase, body, optional ordering, gate and barriers.
Returns#
string

Returns the unique explicit or generated system name.

Raises#
Type Condition
string when another registered system carries that name.

registerPhasemethod#

function(exclusive self: World, phase: PhaseDefinition)

Registers a custom leaf or tree without adding it to the default frame loop.

Arguments#
exclusive self - World
The world whose phase registry changes.
phase - PhaseDefinition
The stable name, optional position and registered child names.
Raises#
Type Condition
string for duplicate names, invalid positions, unknown children or registration during dispatch.

removeSystemmethod#

function(exclusive self: World, name: string): boolean
Arguments#
exclusive self - World
name - string
Returns#
boolean

listSystemsmethod#

function(borrows self: World): {SystemInfo}

Reports the next schedule in phase and dependency order.

Arguments#
borrows self - World

The world to inspect without changing any active dispatch.

Returns#
{SystemInfo}

Returns caller-owned metadata, including disabled systems.

Raises#
Type Condition
string when any phase contains an ordering cycle.

setSystemEnabledmethod#

function(
    exclusive self: World,
    name: string,
    enabled: boolean
): (boolean, string?)
Arguments#
exclusive self - World
name - string
enabled - boolean
Returns#
boolean
string?

updatemethod#

function(exclusive self: World, dt: number)
Arguments#
exclusive self - World
dt - number

startupmethod#

function(exclusive self: World)
Arguments#
exclusive self - World

shutdownmethod#

function(exclusive self: World)
Arguments#
exclusive self - World

runPhasemethod#

function(exclusive self: World, phase: PhaseSelection, dt: number?)
Arguments#
exclusive self - World
phase - PhaseSelection
dt - number?

enablePhasemethod#

function(exclusive self: World, phase: PhaseSelection)
Arguments#
exclusive self - World
phase - PhaseSelection

disablePhasemethod#

function(exclusive self: World, phase: PhaseSelection)
Arguments#
exclusive self - World
phase - PhaseSelection

isPhaseEnabledmethod#

function(borrows self: World, phase: Phase): boolean
Arguments#
borrows self - World
phase - Phase
Returns#
boolean

getNominalFrameTimemethod#

function(borrows self: World): number

Returns the configured seconds per presentation tick.

Arguments#
borrows self - World
Returns#
number

setNominalFrameTimemethod#

function(exclusive self: World, seconds: number)

Changes conversion for future sequence waits; existing deadlines stay fixed.

Arguments#
exclusive self - World
seconds - number

getFixedTimingmethod#

function(borrows self: World): (number, number, number)
Arguments#
borrows self - World
Returns#
number
number
number

fixedStepCountmethod#

function(borrows self: World): integer
Arguments#
borrows self - World
Returns#
integer

getStatsmethod#

function(borrows self: World, fill: WorldStats?): WorldStats

Reports current counts and accumulated fixed-step losses.

Arguments#
borrows self - World
The world to inspect.
fill - WorldStats?
The optional caller-owned result to overwrite without allocating.
Returns#
WorldStats

Returns fill itself, or a new record when fill is absent.

createStatemethod#

function(exclusive self: World, name: string, policy: StatePolicy?): Component
Arguments#
exclusive self - World
name - string
policy - StatePolicy?
Returns#
Component

pushStatemethod#

function(exclusive self: World, name: string)
Arguments#
exclusive self - World
name - string

popStatemethod#

function(exclusive self: World)
Arguments#
exclusive self - World

peekStatemethod#

function(borrows self: World): string?
Arguments#
borrows self - World
Returns#
string?

listStatesmethod#

function(borrows self: World): {string}
Arguments#
borrows self - World
Returns#
{string}

newBundlemethod#

function(self: World, name: string, definition: BundleDefinition?): Bundle
Arguments#
self - World
name - string
definition - BundleDefinition?
Returns#
Bundle

spawnBundlemethod#

function(exclusive self: World, name: string, ...: ComponentInput): integer
Arguments#
exclusive self - World
name - string
... - ComponentInput
Returns#
integer

getBundlesmethod#

function(borrows self: World): {[string]: Bundle}
Arguments#
borrows self - World
Returns#
{[string]: Bundle}

getBundlemethod#

function(borrows self: World, name: string): Bundle?
Arguments#
borrows self - World
name - string
Returns#
Bundle?

saveSnapshotmethod#

function(exclusive self: World, options: SnapshotOptions?): Snapshot

Saves committed entities and durable world metadata in table or native binary form.

Arguments#
exclusive self - World
The world to save; staged mutations publish first.
options - SnapshotOptions?
The optional format, file, filters and custom metadata.
Returns#
Snapshot

Returns a detached table snapshot, or with format = "binary" one whose bytes holds the encoded snapshot.

Raises#
Type Condition
string during publication or another suspended dispatch, for invalid options, duplicate or reserved metadata, unencodable values, or failed file output.

saveSnapshotIntomethod#

function(
    exclusive self: World,
    exclusive output: bytes.Buffer,
    options: SnapshotOptions?
): SnapshotPrelude

Saves a native binary snapshot into a buffer the caller owns and reuses.

The buffer is reset first, so it holds exactly this snapshot afterwards, and no per-save string is made unless options.path asks for a file.

Arguments#
exclusive self - World
The world to save; staged mutations publish first.
exclusive output - bytes.Buffer
The bytes.Buffer to replace with the encoded snapshot.
options - SnapshotOptions?
The optional file, filters and custom metadata; format must be nil or "binary".
Returns#
SnapshotPrelude

Returns the saved snapshot prelude.

Raises#
Type Condition
string under the same conditions as saveSnapshot, or for a table format.

loadSnapshotmethod#

function(exclusive self: World, snapshot: any): SnapshotPrelude

Replaces entity state while retaining registered runtime setup.

Arguments#
exclusive self - World
The destination with component and state definitions already registered.
snapshot - any
The current or version-one table, a binary snapshot, or its encoded byte string.
Returns#
SnapshotPrelude

Returns the validated snapshot prelude.

Raises#
Type Condition
string during publication or another suspended dispatch, or for invalid framing, identities, schemas, state or codecs.

loadSnapshotFrommethod#

function(exclusive self: World, borrows input: bytes.Buffer): SnapshotPrelude

Replaces entity state from a binary snapshot held in a buffer, as loadSnapshot does from its bytes.

The buffer is only read: it keeps its contents, so one saved checkpoint can be loaded again. Its unread bytes are copied once to parse them.

Arguments#
exclusive self - World
The destination with component and state definitions already registered.
borrows input - bytes.Buffer
The bytes.Buffer holding exactly one encoded snapshot.
Returns#
SnapshotPrelude

Returns the validated snapshot prelude.

Raises#
Type Condition
string under the same conditions as loadSnapshot.

addSnapshotHandlermethod#

function(exclusive self: World, handler: SnapshotHandler)
Arguments#
exclusive self - World
handler - SnapshotHandler

observemethod#

function<E is Emittable>(
    exclusive self: World,
    address: integer,
    event: Type<E>,
    callback: Observer<E>,
    id: string?
)
Type parameters#
Name Description
E
Arguments#
exclusive self - World
address - integer
event - Type<E>
callback - Observer<E>
id - string?

observeOncemethod#

function<E is Emittable>(
    exclusive self: World,
    address: integer,
    event: Type<E>,
    callback: Observer<E>,
    id: string?
)
Type parameters#
Name Description
E
Arguments#
exclusive self - World
address - integer
event - Type<E>
callback - Observer<E>
id - string?

stopObservingmethod#

function<E is Emittable>(
    exclusive self: World,
    address: integer,
    event: Type<E>,
    callbackOrId: Observer<E> | string
): boolean
Type parameters#
Name Description
E
Arguments#
exclusive self - World
address - integer
event - Type<E>
callbackOrId - Observer<E> | string
Returns#
boolean

hasObserversmethod#

function<E is Emittable>(
    borrows self: World,
    address: integer,
    event: Type<E>
): boolean
Type parameters#
Name Description
E
Arguments#
borrows self - World
address - integer
event - Type<E>
Returns#
boolean

emitmethod#

function<E is Emittable>(
    exclusive self: World,
    address: integer,
    event: Type<E>,
    ...: unpackof Construction(E)
)
Type parameters#
Name Description
E
Arguments#
exclusive self - World
address - integer
event - Type<E>
... - unpackof Construction(E)

delivermethod#

function<E is Emittable>(
    exclusive self: World,
    address: integer,
    event: Type<E>,
    instance: E
)
Type parameters#
Name Description
E
Arguments#
exclusive self - World
address - integer
event - Type<E>
instance - E

clearObserversmethod#

function(exclusive self: World, address: integer)
Arguments#
exclusive self - World
address - integer

WorldConfigtype#

type WorldConfig = {
    nominalFrameTime: number?,
    maxEntities: integer?,
    timestep: number?,
    fixedMaxSteps: integer?,
    fixedOverload: FixedOverload?,
    pipelineFactory: (function(): Pipeline)?
}

The options accepted by newWorld.

Members#

nominalFrameTimefield#

nominalFrameTime: number?

Caller-writable. Sets seconds per presentation tick, defaulting to 1/60 even headless.

maxEntitiesfield#

maxEntities: integer?

timestepfield#

timestep: number?

fixedMaxStepsfield#

fixedMaxSteps: integer?

fixedOverloadfield#

fixedOverload: FixedOverload?

pipelineFactoryfield#

pipelineFactory: (function(): Pipeline)?

Caller-writable. Replaces the scheduler before built-in systems are installed.

WorldStatsrecord#

record WorldStats

Fixed-step overload counters accumulated by a world.

Members#

constructorconstructor#

function(
    entities: integer,
    archetypes: integer,
    components: integer,
    systems: integer,
    fixedTimeDropped: number,
    fixedStepsDropped: integer
): tecs.ecs.WorldStats

Constructs an instance from named fields. Optional fields may be omitted.

Arguments#
entities - integer
Required.
archetypes - integer
Required.
components - integer
Required.
systems - integer
Required.
fixedTimeDropped - number
Required.
fixedStepsDropped - integer
Required.
Returns#
tecs.ecs.WorldStats

the constructed instance

Examples#

Using values of the argument types above:

local value = require("tecs.ecs").WorldStats(
    entities = entities,
    archetypes = archetypes,
    components = components,
    systems = systems,
    fixedTimeDropped = fixedTimeDropped,
    fixedStepsDropped = fixedStepsDropped
)

entitiesfield#

entities: integer

archetypesfield#

archetypes: integer

componentsfield#

components: integer

systemsfield#

systems: integer

fixedTimeDroppedfield#

fixedTimeDropped: number

fixedStepsDroppedfield#

fixedStepsDropped: integer

Values#

ChildOfvariable#

const ChildOf: Relationship

Relates one child entity to its parent.

world:spawn(ChildOf(parent)) places an entity under parent, and world:set(child, ChildOf(other)) reparents it at the next barrier. The relationship is exclusive, reverse indexed and cascading: a child has one parent, world:relationshipSources(ChildOf, parent) answers with that parent's children, and despawning a parent despawns the tree beneath it.

DEFAULT_FIXED_MAX_STEPSvariable#

const DEFAULT_FIXED_MAX_STEPS: integer

The per-frame fixed-step limit used when newWorld receives no override.

DEFAULT_MAX_ENTITIESvariable#

const DEFAULT_MAX_ENTITIES: integer

The entity capacity used when newWorld receives no override.

DEFAULT_TIMESTEPvariable#

const DEFAULT_TIMESTEP: number

The fixed update interval used when newWorld receives no override.

Disabledvariable#

const Disabled: TagComponent

Marks entities disabled by a state policy.

EntityKeyvariable#

const EntityKey: ScalarComponent<string>

Stores a durable unique name for one entity.

A key names at most one live entity, and World.byKey answers with the entity holding it. Claiming a key another live entity already holds raises, since nothing later could resolve which of the two a lookup means.

The component is registered under the name Key, which is what a snapshot records. That spelling is a compatibility surface and does not follow this public name.

MAX_ENTITIESvariable#

const MAX_ENTITIES: integer

The greatest entity capacity supported by the packed id format.

Namevariable#

const Name: ScalarComponent<string>

Names an entity for a human reader.

A name is neither indexed nor unique. EntityKey is what a lookup resolves through; this is what a debug overlay prints.

newRelationshipvariable#

const newRelationship: NewRelationship

Registers a target-only relationship or a record or struct payload declaration. The one-argument options form creates target-only edges. The declaration form selects managed or native payload storage without running a user constructor.

Raises#

Type Condition
string when cascade deletion lacks exclusivity or reverse indexing.
string when the name is invalid or already belongs to another definition.
string when a payload declaration does not provide a valid target field.
string when a native layout is unsupported or snapshot codecs are incomplete.

newScalarComponentvariable#

const newScalarComponent: NewScalarComponent

Creates and registers a scalar component whose column stores raw values.

Raises#

Type Condition
string when the name is empty or already registered

Pausedvariable#

const Paused: TagComponent

Marks entities paused by a state policy.

PreviousTransform2Dvariable#

const PreviousTransform2D: ComponentDefinition<PreviousTransform2D>

Opts an entity into fixed-step presentation interpolation. Physics seeds this with the body's creation pose. The builtin snapshot system refreshes it before each fixed step; rendering never mutates simulation.

RelativeTransform2Dvariable#

const RelativeTransform2D: ComponentDefinition<RelativeTransform2D>

Constructs an offset from a parent's transform.

Spawn it beside Transform2D and ChildOf. The builtin RelativeTransform2D system composes the parent's world transform with the offset and writes the result into the entity's own Transform2D, so a renderer, a query, or a physics body keeps reading one transform.

Transform2Dvariable#

const Transform2D: ComponentDefinition<Transform2D>

Constructs the shared two-dimensional transform component.

Transform3Dvariable#

const Transform3D: ComponentDefinition<Transform3D>

Constructs a 3D transform, defaulting to the identity at the origin.

TTLvariable#

const TTL: ComponentDefinition<TTL>

Constructs a lifetime that despawns its entity when it runs out.

world:spawn(TTL(0.5)) gives an entity half a second of fixed time. The builtin ttl system spends it one fixed step at a time and despawns the entity at zero, and ttl:percentComplete() reports how much of the original budget is gone.

Annotations#

componentAnnotation#

record component ...
@annotation(targets={"record","struct"})

Configures a derived component's persisted identity and snapshot policy.

Values#

fields

namefield#

name: string?

Caller-writable. Pins the persisted name; nil uses the qualified declaration.

transientfield#

transient: boolean?

Caller-writable. Omits this component's values from snapshots.

relationshipAnnotation#

record relationship ...
@annotation(targets={"record","struct"})

Configures a derived relationship's identity, cardinality and storage policy.

Values#

namefield#

name: string?

Caller-writable. Pins the persisted name; nil uses the qualified declaration.

transientfield#

transient: boolean?

Caller-writable. Omits this relationship from snapshots.

exclusivefield#

exclusive: boolean?

Caller-writable. Limits each source to one target when true.

sparsefield#

sparse: boolean?

Caller-writable. Selects entity-indexed edges instead of dense target columns.

reverseIndexfield#

reverseIndex: boolean?

Caller-writable. Maintains target-to-source lookup when true.

cascadeDeletefield#

cascadeDelete: boolean?

Caller-writable. Deletes sources with their target; requires both index and exclusivity.