tecs.ecs#
Overview#
functions
declaredComponentsdefinitionfindComponentByIdfindComponentByNamenewComponentnewTagComponentnewWorldtargeting
comptime
submodules
types
ArchetypeArchetypeCreatedArchetypeEntityObserverBatchCallbackBundleBundleDefinitionComponentComponentDefinitionComponentInputComponentOptionsComponentValueDoubleArrayEdgeOptionsEntityLifecycleFinishSnapshotLoadFixedOverloadNewRelationshipOnDespawnOnSnapshotSaveOnSpawnPhasePhaseDefinitionPhaseGroupPhaseSelectionPipelinePreviousTransform2DQueryQueryDescriptorRelationshipRelationshipDefinitionRelationshipOptionsRelationshipPayloadRelationshipValueRelativeTransform2DRunIfScalarComponentScalarComponentOptionsSnapshotSnapshotHandlerSnapshotOptionsSnapshotPreludeStartSnapshotLoadStateBlurStateBlurChangeStateChangeStateEnterStateExitStateFocusStateFocusChangeStatePolicySystemSystemConfigSystemInfoTagComponentOptionsTransform2DTransform3DTTLWorldWorldConfigWorldStats
values
ChildOfDEFAULT_FIXED_MAX_STEPSDEFAULT_MAX_ENTITIESDEFAULT_TIMESTEPDisabledEntityKeyMAX_ENTITIESNamenewRelationshipnewScalarComponentPausedPreviousTransform2DRelativeTransform2DTransform2DTransform3DTTL
annotations
Functions#
Componentcomptime#
function(info: types.derive.Info): types.derive.Result<derived.Value>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>): ComponentReturns 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): ComponentCreates 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?): WorldCreates 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#
function(info: types.derive.Info): types.derive.Result<derived.Edge>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 ArchetypeA dense archetype returned by query iteration.
Members#
instance methods
addEntityObserveranyComponentDirtyclearDirtyComponentsdirtyComponentsforEachRelationshipgetgetFirstRelationshipgetMutisComponentDirtymarkAllComponentsDirtymarkComponentDirtysetstructuralAddedstructuralCountstructuralDescribedstructuralTouchedtrackValueCountvalueCountwriteCount
fields
idfield#
id: integersignaturefield#
signature: stringcomponentIdsfield#
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): booleanReports 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): integerReturns 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): integerCounts 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-Archetypecomponent-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-Archetypecomponent-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-Archetypecomponent-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-Archetypecomponent-Type<T>
Returns#
derived.Column(T,RelationshipPayload)?
isComponentDirtymethod#
function(self: Archetype, component: components.Selector): booleanArguments#
self-Archetypecomponent-components.Selector
Returns#
boolean
anyComponentDirtymethod#
function(self: Archetype): booleanArguments#
self-Archetype
Returns#
boolean
markComponentDirtymethod#
function(self: Archetype, component: components.Selector)Arguments#
self-Archetypecomponent-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): integerReturns the structural write count, which survives dirty-bit clearing.
Arguments#
self-Archetype
Returns#
integer
writeCountmethod#
function(self: Archetype, component: components.Selector): integerReturns one column's write count, which survives dirty-bit clearing.
Arguments#
self-Archetypecomponent-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 ArchetypeCreatedReports newly registered archetypes at the world's zero address.
Members#
constructorconstructor#
function(archetype: Archetype): tecs.ecs.ArchetypeCreatedConstructs 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 ArchetypeEntityObserverReceives 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-ArchetypefirstRow-integerlastRow-integercount-integer
Bundlerecord#
record BundleA reusable world-bound spawn shape.
Members#
namefield#
name: stringrequiredfield#
required: {string}defaultedfield#
defaulted: {string}spawnmethod#
function(self: Bundle, ...: ComponentInput): integerArguments#
self-Bundle...-ComponentInput
Returns#
integer
BundleDefinitiontype#
type BundleDefinition = {
required: {components.Selector}?,
with: {[components.Selector]: true | BundleFactory}?
}Required and defaulted components for a bundle.
Members#
requiredfield#
required: {components.Selector}?withfield#
with: {[components.Selector]: true | BundleFactory}?Componentinterface#
interface ComponentA process-wide component definition.
Members#
Valuefield#
Value: associatedDeclColumnfield#
Column: associatedDeclcomponentIdfield#
componentId: integercomponentNamefield#
componentName: stringstorageTypefield#
storageType: stringtransientfield#
transient: booleanComponentDefinitioninterface#
interface ComponentDefinition<T> is ComponentA named definition with its column type selected from the value declaration.
Type parameters#
| Name | Description |
|---|---|
T |
Members#
implements
static methods
metamethods
fields
Valuefield#
Value: associatedDeclColumnfield#
Column: associatedDeclconstructmethod#
function(...: any): TArguments#
...-any
Returns#
T
defaultFactorymethod#
function(): TReturns#
T
snapshotSavemethod#
function(value: T): anyArguments#
value-T
Returns#
any
snapshotLoadmethod#
function(value: any, exclusive world: any): TArguments#
value-anyexclusive world-any
Returns#
T
__call#
function(
self,
...: any
): tecs.gfx.models.BoundsInput<T, ComponentDefinition<T>>Arguments#
?-self...-any
Returns#
ComponentInputtype#
type ComponentInput = Component
| Type<ComponentValue>
| ComponentValue
| ScalarInstance<any>
| TableInstance<any>
| tecs.gfx.models.BoundsInput<any, any>
| RelationshipInstance
| RelationshipBatchA 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 ComponentValueBounds generic helpers to records or structs deriving the component contract.
DoubleArrayinterface#
interface DoubleArrayExposes the native, one-based packed entity ID column and its exact length.
Members#
metamethods
__len#
function(self: DoubleArray): integerArguments#
self-DoubleArray
Returns#
integer
__index#
function(self: DoubleArray, index: integer): integerArguments#
self-DoubleArrayindex-integer
Returns#
integer
__newindex#
function(self: DoubleArray, index: integer, id: integer?)Arguments#
self-DoubleArrayindex-integerid-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 | OnDespawnThe payload shared by entity spawn and despawn lifecycle events.
FinishSnapshotLoadrecord#
record FinishSnapshotLoadReports completion of snapshot metadata restoration.
Members#
constructorconstructor#
function(prelude: SnapshotPrelude): tecs.ecs.FinishSnapshotLoadConstructs 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): RelationshipArguments#
options-RelationshipOptions
Returns#
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#
OnDespawnrecord#
record OnDespawnFires at the entity address and address zero immediately before removal.
Members#
constructorconstructor#
function(
entity: integer,
source: Archetype,
row: integer,
requestedDespawns: {integer}
): tecs.ecs.OnDespawnConstructs 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: integersourcefield#
source: Archetype
Engine-owned. Identifies the entity's last committed archetype.
rowfield#
row: integerEngine-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-OnDespawncomponent-C
Returns#
C.Value?
despawnmethod#
function(self: OnDespawn, entity: integer)Stages another entity for despawn at the same commit barrier.
Arguments#
self-OnDespawnentity-integer
OnSnapshotSaverecord#
record OnSnapshotSaveAllows snapshot participants to attach metadata and exclude regenerated entities.
Members#
constructorconstructor#
function(data: {[string]: any}, excluded: {Component}): tecs.ecs.OnSnapshotSaveConstructs 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 OnSpawnFires at address zero after an entity becomes committed and alive.
Members#
constructorconstructor#
function(entity: integer): tecs.ecs.OnSpawnConstructs 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: integerPhasetype#
type Phase = stringA frame phase.
PhaseDefinitiontype#
type PhaseDefinition = {
name: string,
position: integer?,
children: {string}?
}Declares a custom phase or ordered phase tree.
Members#
namefield#
name: stringCaller-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 | PhaseGroupA leaf phase or predefined group accepted by schedule controls.
Pipelineinterface#
interface PipelineImplements custom scheduling while the world owns entities and task scopes.
Members#
countfield#
count: integerRead-only. Reports the registered system count.
fixedTimestepfield#
fixedTimestep: numberRead-only. Reports the fixed-step duration in seconds.
fixedMaxStepsfield#
fixedMaxSteps: integerRead-only. Limits catch-up iterations in one frame.
fixedOverloadfield#
fixedOverload: FixedOverload
Read-only. Selects drop or accumulate for excess fixed time.
fixedAccumulatorfield#
fixedAccumulator: numberEngine-owned. Stores the fixed remainder; snapshot restore writes it.
fixedStepCountfield#
fixedStepCount: integerRead-only. Reports completed fixed iterations.
fixedTimeDroppedfield#
fixedTimeDropped: numberRead-only. Reports abandoned fixed time in seconds.
fixedStepsDroppedfield#
fixedStepsDropped: integerRead-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#
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): stringRegisters 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): booleanRemoves 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): booleanReports whether a leaf is enabled.
Arguments#
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 ...Stores the position and rotation before the current fixed step.
Members#
xfield#
x: numberEngine-owned. Stores the previous horizontal position in world units.
yfield#
y: numberEngine-owned. Stores the previous vertical position in world units.
rotationfield#
rotation: numberEngine-owned. Stores the previous clockwise rotation in radians.
Queryrecord#
record QueryA 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#
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.
Queryinteger?
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.
GroupStateArchetype?
getGroupmethod#
function(self: Query, candidate: Archetype): integer?Returns an archetype's assigned group.
Arguments#
Returns#
integer?-
Returns nil when unmatched or ungrouped.
getGroupCountmethod#
function(self: Query, groupId: integer): integerCounts 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): integerCounts 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 ComponentA target-only entity relationship with selectable cardinality and storage.
Members#
implements
constructors
instance methods
metamethods
fields
constructorconstructor#
function(
componentId: integer,
componentName: string,
storageType: string,
transient: boolean,
exclusive: boolean,
reverseIndex: boolean,
cascadeDelete: boolean,
sparse: boolean
): tecs.ecs.RelationshipConstructs 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: associatedDeclcomponentIdfield#
componentId: integercomponentNamefield#
componentName: stringstorageTypefield#
storageType: stringtransientfield#
transient: booleanexclusivefield#
exclusive: booleanreverseIndexfield#
reverseIndex: booleancascadeDeletefield#
cascadeDelete: booleansparsefield#
sparse: booleanRead-only. Selects entity-indexed edge storage; false selects target-specific dense columns.
__call#
function(self, target: integer): RelationshipInstanceArguments#
?-selftarget-integer
Returns#
RelationshipInstance
targetingmethod#
function(self: Relationship, target: integer): RelationshipReturns 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 ComponentA 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: associatedDeclColumnfield#
Column: associatedDeclconstructmethod#
function(...: any): TArguments#
...-any
Returns#
T
defaultFactorymethod#
function(): TReturns#
T
snapshotSavemethod#
function(value: T): anyArguments#
value-T
Returns#
any
snapshotLoadmethod#
function(value: any, exclusive world: any): TArguments#
value-anyexclusive world-any
Returns#
T
__call#
function(
self,
...: any
): tecs.gfx.models.BoundsInput<T, RelationshipDefinition<T>>Arguments#
?-self...-any
Returns#
targetingmethod#
function(
self: RelationshipDefinition<T>,
target: integer
): ComponentDefinition<T>Arguments#
self-RelationshipDefinition<T>target-integer
Returns#
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: stringCaller-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 ComponentValueBounds generic helpers to target-bearing declarations deriving the relationship contract.
Members#
implements
RelationshipValuerecord#
record RelationshipValueA target-only relationship edge value.
Members#
constructorconstructor#
function(target: integer): tecs.ecs.RelationshipValueConstructs 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: integerRead-only. Names the target; replace the edge through world:set to retarget it.
RelativeTransform2Dstruct#
struct RelativeTransform2D ...Offsets an entity from the transform of the parent it names with ChildOf.
Members#
xfield#
x: numberCaller-writable. Sets the horizontal offset from the parent, in the parent's rotated and scaled space.
yfield#
y: numberCaller-writable. Sets the vertical offset from the parent, in the parent's rotated and scaled space.
zfield#
z: numberCaller-writable. Sets the depth offset added to the parent's depth.
rotationfield#
rotation: numberCaller-writable. Sets the clockwise rotation in radians added to the parent's rotation.
scaleXfield#
scaleX: numberCaller-writable. Sets the horizontal scale multiplied by the parent's.
scaleYfield#
scaleY: numberCaller-writable. Sets the vertical scale multiplied by the parent's.
originXfield#
originX: numberCaller-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: numberCaller-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): booleanA predicate receiving the phase delta, world and registered system name.
Arguments#
dt-numberexclusive world-WorldsystemName-string
Returns#
boolean
ScalarComponentrecord#
record ScalarComponent<T> is ComponentA primitive-valued component definition.
Type parameters#
| Name | Description |
|---|---|
T |
Members#
implements
constructors
metamethods
fields
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: associatedDeclcomponentIdfield#
componentId: integercomponentNamefield#
componentName: stringstorageTypefield#
storageType: stringtransientfield#
transient: booleanscalarKindfield#
scalarKind: "number" | "boolean" | "string"scalarDefaultfield#
scalarDefault: T__call#
function(self, value: T): ScalarInstance<T>Arguments#
?-selfvalue-T
Returns#
ScalarInstance<T>
ScalarComponentOptionstype#
type ScalarComponentOptions = NumberComponentOptions | BooleanComponentOptions | StringComponentOptionsOptions accepted by the kind-correlated scalar component factory.
Snapshotrecord#
record SnapshotA detached, format-neutral world snapshot.
Members#
constructors
fields
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.SnapshotConstructs 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 whenformatis"binary". The string is the caller's to keep, write to a file or pass toloadSnapshot.
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: integernextEntityIdfield#
nextEntityId: integerentityCountfield#
entityCount: integerarchetypeCountfield#
archetypeCount: integercomponentTablefield#
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: stringsavefield#
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#
fields
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 SnapshotPreludeMetadata returned by a snapshot load.
Members#
constructorconstructor#
function(
version: integer,
nextEntityId: integer,
entityCount: integer,
archetypeCount: integer,
componentTable: {SnapshotComponentEntry}
): tecs.ecs.SnapshotPreludeConstructs 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: integerRead-only. Reports the ECS framing version, independently of game data versions.
nextEntityIdfield#
nextEntityId: integerRead-only. Reports the next fresh entity slot after restoration.
entityCountfield#
entityCount: integerRead-only. Reports the number of saved entities.
archetypeCountfield#
archetypeCount: integerRead-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 StartSnapshotLoadAllows snapshot participants to subscribe to metadata during a load.
Members#
constructorconstructor#
function(
prelude: SnapshotPrelude,
handlers: {[string]: {function(value: any)}}
): tecs.ecs.StartSnapshotLoadConstructs 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 StateBlurFires after the current state loses focus.
Members#
constructorconstructor#
function(state: string, pushed: string): tecs.ecs.StateBlurConstructs 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: stringpushedfield#
pushed: stringStateBlurChangerecord#
record StateBlurChangeThe payload emitted when a state loses focus.
Members#
constructorconstructor#
function(state: string, pushed: string): tecs.ecs.StateBlurChangeConstructs 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: stringpushedfield#
pushed: stringStateChangetype#
type StateChange = StateEnter | StateExitThe payload emitted when a state enters or exits.
StateEnterrecord#
record StateEnterFires after a state becomes active.
Members#
constructorconstructor#
function(state: string): tecs.ecs.StateEnterConstructs 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: stringStateExitrecord#
record StateExitFires before a state leaves the stack.
Members#
constructorconstructor#
function(state: string): tecs.ecs.StateExitConstructs 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: stringStateFocusrecord#
record StateFocusFires after an uncovered state regains focus.
Members#
constructorconstructor#
function(state: string, popped: string): tecs.ecs.StateFocusConstructs 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: stringpoppedfield#
popped: stringStateFocusChangerecord#
record StateFocusChangeThe payload emitted when a state regains focus.
Members#
constructorconstructor#
function(state: string, popped: string): tecs.ecs.StateFocusChangeConstructs 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: stringpoppedfield#
popped: stringStatePolicytype#
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-numberexclusive world-Worldborrows 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#
fields
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: stringRead-only. Names the registered system.
phasefield#
phase: Phase
Read-only. Names its dispatch phase.
positionfield#
position: integerRead-only. Reports its position in the inspected schedule.
enabledfield#
enabled: booleanRead-only. Reports whether the scheduler permits dispatch.
hasRunIffield#
hasRunIf: booleanRead-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: stringtransientfield#
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 ...Places an entity in the two-dimensional world.
Members#
xfield#
x: numberCaller-writable. Sets the horizontal position in world units.
yfield#
y: numberCaller-writable. Sets the vertical position in world units.
zfield#
z: numberCaller-writable. Sets depth within the selected layer.
layerfield#
layer: integerCaller-writable. Selects the integer draw layer.
rotationfield#
rotation: numberCaller-writable. Sets clockwise rotation in radians.
scaleXfield#
scaleX: numberCaller-writable. Sets horizontal scale in world units.
scaleYfield#
scaleY: numberCaller-writable. Sets vertical scale in world units.
Transform3Dstruct#
struct Transform3D ...Places an entity in a right-handed 3D world using a quaternion and per-axis scale.
Members#
xfield#
x: numberyfield#
y: numberzfield#
z: numberrotationXfield#
rotationX: numberrotationYfield#
rotationY: numberrotationZfield#
rotationZ: numberrotationWfield#
rotationW: numberscaleXfield#
scaleX: numberscaleYfield#
scaleY: numberscaleZfield#
scaleZ: numberTTLstruct#
struct TTL ...Counts down an entity's remaining lifetime.
Members#
startingTimefield#
startingTime: numberCaller-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: numberCaller-writable. Sets the seconds of fixed time left before the entity is despawned. Writing a larger value refreshes the timer.
percentCompletemethod#
function(self: TTL): numberReturns 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 WorldA Tecs world.
Members#
instance methods
addSnapshotHandleraddSystembatchDespawnbatchRemovebatchSetbatchSpawnbatchSpawnAtbatchSpawnAtRawbyKeyclearEntitiesclearObserverscommitcompactcreateStatedeliverdespawndirtyArchetypesdisablePhaseemitenablePhaseenqueueCommitfindArchetypesfixedStepCountforEachArchetypeforEachRelationshipgetgetBundlegetBundlesgetFirstRelationshipgetFixedTiminggetMutgetNominalFrameTimegetStatshashasObserversisAliveisPhaseEnabledlistStateslistSystemsloadSnapshotloadSnapshotFrommarkComponentDirtynewBundlenewQueryobserveobserveOncepeekStatepopStatepushStaterandomStreamregisterPhaserelationshipSourcesremoveremoveSystemrequireKeyrunPhasesaveSnapshotsaveSnapshotIntoseedRandomsetsetNominalFrameTimesetSystemEnabledshutdownspawnspawnAtspawnBundlestartupstopObservingtargetstraverseupdatewalkUp
fields
liveCountfield#
liveCount: integerarchetypeCountfield#
archetypeCount: integersystemCountfield#
systemCount: integerobserversfield#
observers: nuppevents.MessageBus<integer>Observer registrations by address and event; observers:count() is how many are live.
resourcesfield#
resources: Storespawnmethod#
function(exclusive self: World, ...: ComponentInput): integerArguments#
exclusive self-World...-ComponentInput
Returns#
integer
spawnAtmethod#
function(exclusive self: World, id: integer, ...: ComponentInput)Arguments#
exclusive self-Worldid-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#
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): booleanArguments#
borrows self-Worldid-integer
Returns#
boolean
hasmethod#
function(
borrows self: World,
id: integer,
component: components.Selector
): booleanArguments#
borrows self-Worldid-integercomponent-components.Selector
Returns#
boolean
byKeymethod#
function(borrows self: World, key: string): integer?Arguments#
borrows self-Worldkey-string
Returns#
integer?
requireKeymethod#
function(borrows self: World, key: string): integerArguments#
borrows self-Worldkey-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-Worldid-integercomponent-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-Worldid-integercomponent-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-Worldid-integercomponent-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-Worldid-integercomponent-Type<T>
Returns#
T?
markComponentDirtymethod#
function(exclusive self: World, id: integer, component: components.Selector)Arguments#
exclusive self-Worldid-integercomponent-components.Selector
relationshipSourcesmethod#
function(
borrows self: World,
relationship: components.Selector,
target: integer
): {integer}Arguments#
borrows self-Worldrelationship-components.Selectortarget-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?): QueryCreates 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-Worldid-integerinput-ComponentInputvalue-any?
removemethod#
function(exclusive self: World, id: integer, input: ComponentInput)Arguments#
exclusive self-Worldid-integerinput-ComponentInput
despawnmethod#
function(exclusive self: World, id: integer)Arguments#
exclusive self-Worldid-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.Xoshiro128Returns 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): stringRegisters 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): booleanArguments#
exclusive self-Worldname-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-Worldname-stringenabled-boolean
Returns#
booleanstring?
updatemethod#
function(exclusive self: World, dt: number)Arguments#
exclusive self-Worlddt-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-Worldphase-PhaseSelectiondt-number?
enablePhasemethod#
function(exclusive self: World, phase: PhaseSelection)Arguments#
exclusive self-Worldphase-PhaseSelection
disablePhasemethod#
function(exclusive self: World, phase: PhaseSelection)Arguments#
exclusive self-Worldphase-PhaseSelection
isPhaseEnabledmethod#
function(borrows self: World, phase: Phase): booleanArguments#
Returns#
boolean
getNominalFrameTimemethod#
function(borrows self: World): numberReturns 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-Worldseconds-number
getFixedTimingmethod#
function(borrows self: World): (number, number, number)Arguments#
borrows self-World
Returns#
numbernumbernumber
fixedStepCountmethod#
function(borrows self: World): integerArguments#
borrows self-World
Returns#
integer
getStatsmethod#
function(borrows self: World, fill: WorldStats?): WorldStatsReports 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?): ComponentArguments#
exclusive self-Worldname-stringpolicy-StatePolicy?
Returns#
pushStatemethod#
function(exclusive self: World, name: string)Arguments#
exclusive self-Worldname-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?): BundleArguments#
self-Worldname-stringdefinition-BundleDefinition?
Returns#
spawnBundlemethod#
function(exclusive self: World, name: string, ...: ComponentInput): integerArguments#
exclusive self-Worldname-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-Worldname-string
Returns#
saveSnapshotmethod#
function(exclusive self: World, options: SnapshotOptions?): SnapshotSaves 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 whosebytesholds 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?
): SnapshotPreludeSaves 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.Bufferto replace with the encoded snapshot. options-SnapshotOptions?- The optional file, filters and custom metadata;
formatmust 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): SnapshotPreludeReplaces 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): SnapshotPreludeReplaces 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.Bufferholding 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-Worldhandler-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-Worldaddress-integerevent-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-Worldaddress-integerevent-Type<E>callback-Observer<E>id-string?
stopObservingmethod#
function<E is Emittable>(
exclusive self: World,
address: integer,
event: Type<E>,
callbackOrId: Observer<E> | string
): booleanType parameters#
| Name | Description |
|---|---|
E |
Arguments#
exclusive self-Worldaddress-integerevent-Type<E>callbackOrId-Observer<E> | string
Returns#
boolean
hasObserversmethod#
function<E is Emittable>(
borrows self: World,
address: integer,
event: Type<E>
): booleanType parameters#
| Name | Description |
|---|---|
E |
Arguments#
borrows self-Worldaddress-integerevent-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-Worldaddress-integerevent-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-Worldaddress-integerevent-Type<E>instance-E
clearObserversmethod#
function(exclusive self: World, address: integer)Arguments#
exclusive self-Worldaddress-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 WorldStatsFixed-step overload counters accumulated by a world.
Members#
constructors
fields
constructorconstructor#
function(
entities: integer,
archetypes: integer,
components: integer,
systems: integer,
fixedTimeDropped: number,
fixedStepsDropped: integer
): tecs.ecs.WorldStatsConstructs 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: integerarchetypesfield#
archetypes: integercomponentsfield#
components: integersystemsfield#
systems: integerfixedTimeDroppedfield#
fixedTimeDropped: numberfixedStepsDroppedfield#
fixedStepsDropped: integerValues#
ChildOfvariable#
const ChildOf: RelationshipRelates 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: integerThe per-frame fixed-step limit used when newWorld receives no override.
DEFAULT_MAX_ENTITIESvariable#
const DEFAULT_MAX_ENTITIES: integerThe entity capacity used when newWorld receives no override.
DEFAULT_TIMESTEPvariable#
const DEFAULT_TIMESTEP: numberThe fixed update interval used when newWorld receives no override.
Disabledvariable#
const Disabled: TagComponentMarks 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: integerThe 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: NewRelationshipRegisters 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: NewScalarComponentCreates 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: TagComponentMarks 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 ...Configures a derived component's persisted identity and snapshot policy.
Values#
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 ...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.