State machines
hsm is a small typed hierarchical state machine library that ships with the toolchain and compiles to plain Lua. It replaces the if (self.state === ...) branches that otherwise spread across update and on_message. Learn it in the tutorial, copy a snippet from the cheat sheet, or look a field up in the reference.
Import it
hsm needs no install: its declarations ship in @defold-typescript/types, and the build compiles its source.
import { defineMachine } from "@defold-typescript/types/hsm";
import { messageEvents } from "@defold-typescript/types/hsm/defold";| Module | Holds | Written to |
|---|---|---|
@defold-typescript/types/hsm | the machine | lib/defold_typescript/hsm/index.lua |
@defold-typescript/types/hsm/builder | machines written as statements | lib/defold_typescript/hsm/builder.lua, beside the machine's index.lua |
@defold-typescript/types/hsm/defold | the message bridge | lib/defold_typescript/hsm/defold.lua |
@defold-typescript/types/hsm/debug | the debug inspector | lib/defold_typescript/hsm/debug.lua |
@defold-typescript/types/hsm/async | scripted sequences | lib/defold_typescript/hsm/async.lua, and lib/defold_typescript/lualib_bundle.lua for its promises |
buildandwatchwrite each module your code uses to the runtime folder (lib/defold_typescript/hsm/by default), insideoutDirwhen one is set. A module nothing uses, or only uses for its types, is not written.- A source of your own that would compile to one of those paths fails the build.
- The library upgrades with the CLI, and a project scaffolded by
initgitignores the runtime folder. - Each module is written with a source map that points at the library's own
.ts, which ships inside the installed@defold-typescript/transpilerpackage under itsdist/hsm/folder. A debugger frame inside the library opens that file, andwatchandreloadconsole lines name it when it sits inside your project.
States and paths
A machine is a tree of states. The config passed to defineMachine is the root, a state with states of its own is a compound state and names the initial child to enter, and a state without children is a leaf. The active states form one chain from the root down to a leaf.
import { defineMachine } from "@defold-typescript/types/hsm";
type LampEvent = { type: "TOGGLE" } | { type: "DIM" };
export const lamp = defineMachine<object, LampEvent>()({
initial: "/off",
states: {
off: { on: { TOGGLE: "/on" } },
on: {
initial: "/on/bright",
on: { TOGGLE: "/off" },
states: {
bright: { on: { DIM: "/on/dim" } },
dim: { on: { DIM: "/on/bright" } },
},
},
},
});
const m = lamp.start({});
m.send({ type: "TOGGLE" });
m.path; // "/on/bright"
m.matches("/on"); // true: an ancestor of the current stateA parent holds what its children share: TOGGLE on on applies in bright and in dim, because an event a child does not handle moves up to its parent.
- A path is a leading
/, then the state names from the root down, as in/on/dim. It is howinitial,pathandmatches()name a state, and how a rule names its target. pathis the deepest active state, orundefinedonce the machine has stopped, soif (m.path)means the same in TypeScript and in Lua.matches(p)is true for every active state, ancestors included.- The root has no name.
/alone is not a state, so the root is never a target and never matched. - A state name is non-empty and holds no
/. Any other character is allowed,.and#included.
defineMachine checks the config when the module loads. It throws, naming the state path, on a compound state with no initial, an initial that is not the full path of one of the state's children, a target that names no state, and a state name that is empty or holds /. Most of these fail to compile first; see Types.
Events and transitions
on maps an event's type to a rule. A rule is a target path, an object of to, when and run, each optional, or a non-empty list of those objects, tried in order.
alive: {
initial: "/alive/patrol",
on: {
HIT: [
{ to: "/dead", when: (ctx, event) => ctx.health <= event.damage },
{
run: (ctx, event) => {
ctx.health -= event.damage;
},
},
],
},
states: {
patrol: { on: { SEE_PLAYER: "/alive/chase" } },
chase: { on: { SEE_PLAYER: "/alive/chase", LOSE_PLAYER: "/alive/patrol", FALL: "/dead" } },
},
},const m = buildMachine<EnemyCtx, EnemyEvent>()({
initial: "/alive",
states: {
alive: {
initial: "/alive/patrol",
states: { patrol: {}, chase: {} },
},
dead: {},
},
});
m.state("/alive")
.on("HIT")
.when((ctx, event) => ctx.health <= event.damage)
.to("/dead");
m.state("/alive").on("HIT").run((ctx, event) => {
ctx.health -= event.damage;
});
m.state("/alive/patrol").on("SEE_PLAYER").to("/alive/chase");
m.state("/alive/chase").on("SEE_PLAYER").to("/alive/chase");
m.state("/alive/chase").on("LOSE_PLAYER").to("/alive/patrol");
m.state("/alive/chase").on("FALL").to("/dead");- Which rule runs. An event starts at the deepest active state and moves up to the root. The first rule with no
when, or whosewhenreturnstrue, runs, and the event goes no further:HITsent in/alive/chasereachesalive. An event no rule takes is dropped; see React to an unhandled event. - A rule with no
toruns itsrunand nothing else: no state exits or enters. The secondHITrule is one. - A target is a full path, wherever it is declared.
./patrol,../patroland a barepatrolare not paths, anddefineMachinethrows on them, naming the state that declares them. - Exit,
run, enter. A move runsexitfrom the deepest active state up, then the rule'srun, thenenterdown to the target and on through eachinitial. A fatalHITin/alive/chaserunsexitofchase,exitofalive, therun, thenenterofdead. - Only the states below the nearest one that holds both the source and the target exit and re-enter. A
tobelow the state the rule is on keeps that state:/alive/patrolfromalivechanges the child only. - A rule naming its own state restarts it. The state exits and re-enters, so its timers and its
taskstart over, asSEE_PLAYERinchasedoes. The same holds for anaftertimer, analwaysentry and anupdatehook:after: { 1: "/blink" }onblinkrepeats every second. A target that is an ancestor of the source exits and re-enters that ancestor. - Arguments.
whenandrunreceive(ctx, event, machine), witheventnarrowed to the variant theonkey names.runis one function or a list run in order. Themachineof awhenis a read-only view withpath,leaves,matchesandhasTag. - A
whenhas no side effects. It is also called when the move does not happen: for each candidate of a list, and on everyalwaysrecheck. Write inrun, which is called only when the move happens; the types reject awhenthat assigns toctx.
React to an unhandled event
unhandled on a state is the machine's reaction to any event it did not take, such as refusing a request by name:
initial: "/closed",
// in every state: refuse, by name, whatever request the door did not take
unhandled: (_ctx, event) => msg.post(event.sender, "door_refused", { request: event.type }),
states: {
closed: { on: { open_door: "/open", lock_door: "/locked" } },
open: { on: { close_door: "/closed" } },
locked: {
// in this state only: any request but the unlock rattles the handle
unhandled: (ctx) => sprite.play_flipbook(ctx.sprite, "rattle"),
on: { unlock_door: "/closed" },
},
},const m = buildMachine<DoorCtx, DoorEvent>()({
initial: "/closed",
states: { closed: {}, open: {}, locked: {} },
});
// in every state: refuse, by name, whatever request the door did not take
m.root.unhandled((_ctx, event) =>
msg.post(event.sender, "door_refused", { request: event.type }),
);
m.state("/closed").on("open_door").to("/open");
m.state("/closed").on("lock_door").to("/locked");
m.state("/open").on("close_door").to("/closed");
// in this state only: any request but the unlock rattles the handle
m.state("/locked").unhandled((ctx) => sprite.play_flipbook(ctx.sprite, "rattle"));
m.state("/locked").on("unlock_door").to("/closed");A locked door asked to open rattles its handle, then tells the sender the request was refused; closed and open only refuse. No rule took the request, so can still answers false for it.
- It runs for the events an
onUnhandledlistener hears, and no others. An event a parent state takes runs no hook, on any state. - Every active state that has the hook runs it, deepest first. The regions of a parallel state run in name order and the parallel state after them. The
onUnhandledlisteners run after the hooks. eventis the machine's whole event union. Checkevent.typebefore reading a payload field. A field every variant has, such assenderon a machine that takes only messages, needs no check.- The hook moves nothing. It returns nothing, no state exits or enters, and a
stop()from it ends the step once every hook and listener has run for the event. - A state that should ignore an event takes it with an empty rule. With
PAUSE: {}on the state, neither a parent's rule nor anyunhandledhook runs. - For one named event, write a rule.
HIT: { run }takes the event with its payload narrowed, andcananswerstruefor it.
update and after
m.update(dt) advances the machine by one tick. after maps a delay in seconds to a target path or to a rule, and an update hook returns a path to move to:
grounded: {
update: (ctx) => (ctx.on_ground ? undefined : "/coyote"),
on: { JUMP: "/jumping" },
},
// Just after walking off a ledge, a jump still counts.
coyote: {
update: (ctx) => (ctx.on_ground ? "/grounded" : undefined),
after: { 0.1: "/falling" },
on: { JUMP: "/jumping" },
},m.state("/grounded").update((ctx) => (ctx.on_ground ? undefined : "/coyote"));
m.state("/grounded").on("JUMP").to("/jumping");
// Just after walking off a ledge, a jump still counts.
m.state("/coyote").update((ctx) => (ctx.on_ground ? "/grounded" : undefined));
m.state("/coyote").after(0.1).to("/falling");
m.state("/coyote").on("JUMP").to("/jumping");- Clocks count the
dtpassed in. Every active state addsdtto its own clock on every call and starts from zero each time it is entered, so a machine whoseupdateis not called is frozen in time. updatehooks go first, from the deepest active state up, each with(ctx, dt, machine). A hook returns the path to move to, orundefinedto pass. The first path returned wins: the remaining hooks do not run, and the move has norun.- Timers run only when no hook moved. Each active state, deepest first, then runs its
everyentries and tries itsaftertimers in delay order. Landing on the tickcoyote's timer is due wins over falling. - One timer moves a region per
update. The first timer that moves ends the timers of its region for that call, and another timer that is due waits for the next call. - A state that stays active keeps counting while its children change, so
after: { 2: "/normal" }on a parent ends a blink that its two children pass back and forth every tenth of a second.
A delay that reads the context
after also takes a list. Each entry holds a delay, a number or a function of the context that returns one, beside its to, as in after: [{ delay: (ctx) => ctx.patrolFor, to: "/rest" }]. One keyed machine then serves guards with different delays, because each instance reads its own; the cheat sheet has the snippet.
- The function is read once each time the state is entered, after the state's
enterhook, so the hook can set what the delay reads. - The delay is fixed for that stay, and a change to the context takes effect on the next entry. A delay that must change during a stay belongs in an
updatehook that counts the time and returns the path. - A hot reload reads the function again, and the state's clock keeps its time.
- Timers fire in delay order, and entries with one delay fire in list order.
- A delay that is not a non-negative number throws, naming the state.
Rules on a timer
A timer also takes a rule in place of a target path:
charging: {
after: {
// Code at a set time, without leaving the state.
1: { run: () => sound.play("#beep") },
// Code that belongs to one move.
3: { to: "/idle", run: countTimeout },
},
on: { RELEASE: "/idle" },
},
landing: {
// A minimum time, and then a condition.
after: { 0.3: { to: "/idle", when: (ctx) => ctx.grounded } },
},// Code at a set time, without leaving the state.
m.state("/charging").after(1).run(() => sound.play("#beep"));
// Code that belongs to one move.
m.state("/charging").after(3).to("/idle").run(countTimeout);
m.state("/charging").on("RELEASE").to("/idle");
// A minimum time, and then a condition.
m.state("/landing")
.after(0.3)
.when((ctx) => ctx.grounded)
.to("/idle");- A rule takes
to,when(ctx, machine)andrun(ctx, machine), each optional, and a list entry takes them besidedelay. A rule with neither atonor arunthrows when the machine is defined. - A timer fires at most once per stay.
- A due timer whose
whenfails is tried again on everyupdatecall until it passes or the state is left, solandinglasts at least 0.3 seconds and ends on the first tick that finds the hero on the ground. The timers after it are still tried. - A timer with no
tois not a move: noupdatehook is skipped,alwaysis not rechecked,onMoveis not called, and the call goes on to the next due timer.
Repeat while a state is active
every runs code each time a delay passes while the state is active, such as damage every half second, a spawn or a rate of fire:
firing: {
// A rate of fire read from the context.
every: [{ delay: (ctx) => ctx.fireEvery, run: (ctx) => msg.post(ctx.muzzle, "fire") }],
on: { LOSE: "/cooling" },
},
cooling: {
// A fixed delay, beside a timer that leaves the state.
every: {
0.5: (ctx) => {
ctx.heat -= 1;
},
},
after: { 3: "/idle" },
},// A rate of fire read from the context.
m.state("/firing")
.every((ctx) => ctx.fireEvery)
.run((ctx) => msg.post(ctx.muzzle, "fire"));
m.state("/firing").on("LOSE").to("/cooling");
// A fixed delay, beside a timer that leaves the state.
m.state("/cooling")
.every(0.5)
.run((ctx) => {
ctx.heat -= 1;
});
m.state("/cooling").after(3).to("/idle");everytakes a record of seconds torun, or a list of{ delay, run }whosedelayis read as anafterdelay is.runis one function or a list run in order, called with(ctx, machine). A delay that is not a positive number throws, naming the state.- An entry first runs one delay after the state is entered, then each time another delay has passed on the state's clock. It runs at most once per
updatecall: a long frame runs it once, and its later runs stay on multiples of the delay. - A run is not a move, as a timer with no
tois not. - A state's entries run before its
aftertimers, list entries in list order and a record's shortest delay first. On a call in which anupdatehook or a timer of a deeper state moved, they wait for the next call. - An entry takes no
toand nowhen: anaftertimer leaves the state, and aruntests a condition itself. An effect that depends on the frame time belongs in anupdatehook.
Resume with history
Set restoreDepth on a compound state to make it remember which child was active when it was last left. Every later entry goes back to that child instead of initial, this many levels down:
playing: {
restoreDepth: 1,
initial: "/playing/ground",
on: { PAUSE: "/paused" },
states: {
ground: { on: { JUMP: "/playing/air" } },
air: {
initial: "/playing/air/rise",
states: {
rise: { on: { FALL: "/playing/air/fall" } },
fall: {},
},
},
},
},
paused: { on: { RESUME: "/playing", RESTART: "/playing/ground" } },const m = buildMachine<object, PlayEvent>()({
initial: "/playing",
states: {
playing: {
restoreDepth: 1,
initial: "/playing/ground",
states: {
ground: {},
air: {
initial: "/playing/air/rise",
states: { rise: {}, fall: {} },
},
},
},
paused: {},
},
});
m.state("/playing").on("PAUSE").to("/paused");
m.state("/playing/ground").on("JUMP").to("/playing/air");
m.state("/playing/air/rise").on("FALL").to("/playing/air/fall");
m.state("/paused").on("RESUME").to("/playing");
m.state("/paused").on("RESTART").to("/playing/ground");Pausing in mid-air and sending RESUME lands on /playing/air/rise, running the enter hooks of playing, air and rise.
- The count sets how deep the restore goes. With
1, leaving from/playing/air/fallbrings backair, which is entered through its owninitial. With2it also brings backfall, and"all"brings back every level below the state. - Inner levels restore only through the flagged state. A move that targets
/playing/airentersairthrough itsinitial, unlessairhas arestoreDepthof its own. - A parallel state is not a level. The count passes through it to every region.
- A target inside the state wins.
RESTARTnames/playing/groundand lands there whateverplayingremembers. Every other entry uses the memory: a target of/playingitself, and a parent'sinitialchain that passes through it. - The first entry uses
initial, and each instance keeps its own memory. - What throws.
restoreDepththrows when the machine is defined if it is not a whole number from 1 or"all", if it is larger than the number of levels below the state, or if the state has no child states. All three are also compile errors. The compile check counts a parallel state as a level and follows the tree five levels down, so two mistakes are caught only by the throw: a count too large only because a parallel state is not a level, and a wrong count on a state with more than five levels below it.
Move on at once with always
always lists the targets a state moves to as soon as it is entered, without waiting for an event. Use it for a state that only decides where to go next: a HIT that leads to hurt runs its enter, then moves on to /dead or back to /fine in the same send.
hurt: {
enter: (ctx) => {
ctx.health -= 1;
},
always: [{ to: "/dead", when: (ctx) => ctx.health <= 0 }, { to: "/fine" }],
},m.state("/hurt").enter((ctx) => {
ctx.health -= 1;
});
m.state("/hurt")
.always()
.when((ctx) => ctx.health <= 0)
.to("/dead");
m.state("/hurt").always().to("/fine");- Checked after every move:
start, an event, anaftertimer, a path anupdatehook returned, a hot reload, and anotheralwaysmove. The active states are checked deepest first, after theenterhooks and before the next queued event, and the first candidate whosewhenis missing or passes is taken. - Not checked on a tick or after a rule with no
to. Awhenreadingctxthat arunor anupdatehook changed waits for the next move. To watch a condition every frame, return a target from anupdatehook. - A candidate has no event. It is a
to, an optionalwhen(ctx, machine)and an optionalrun(ctx, machine). A candidate without ato, or with an unknown target, throws when the machine is defined. - Loops throw. At most 10
alwaysmoves follow one move. The 11th throwshsm: state "<path>" took 10 always transitions in a row; check for an always loop, drops the queued events and leaves the instance usable in the state it reached.
Run regions side by side with parallel
A state with type: "parallel" keeps every child active at once. Each child is a region with its own active state, so a player can run and fire independently:
alive: {
type: "parallel",
on: { DIE: "/dead" },
states: {
move: {
initial: "/alive/move/idle",
states: { idle: { on: { START_FIRE: "/alive/move/run" } }, run: {} },
},
weapon: {
initial: "/alive/weapon/ready",
states: {
ready: { on: { START_FIRE: "/alive/weapon/cooldown" } },
cooldown: { after: { 0.5: "/alive/weapon/ready" } },
},
},
},
},const m = buildMachine<object, PlayerEvent>()({
initial: "/alive",
states: {
alive: {
type: "parallel",
states: {
move: {
initial: "/alive/move/idle",
states: { idle: {}, run: {} },
},
weapon: {
initial: "/alive/weapon/ready",
states: { ready: {}, cooldown: {} },
},
},
},
dead: {},
},
});
m.state("/alive").on("DIE").to("/dead");
m.state("/alive/move/idle").on("START_FIRE").to("/alive/move/run");
m.state("/alive/weapon/ready").on("START_FIRE").to("/alive/weapon/cooldown");
m.state("/alive/weapon/cooldown").after(0.5).to("/alive/weapon/ready");- Entering and leaving. Entering
/aliveenters each region through itsinitial, or through the target when the target is inside that region. Leaving it exits the last region first, each one deepest state first, then/aliveitself. - Each region moves on its own. An event is offered to every region in order, and each takes at most its first enabled rule, so
START_FIREmoves both regions in onesend.onMovehears each move with that region's old and new leaf. - The parallel state waits for its regions. An event reaches
/alive's ownon, and bubbles above it, only when no region took it. A region rule that leaves or re-enters/aliveends the offer, so later regions do not see that event. - Ticks and
alwaysrun per region. Each region runs itsupdatehooks, then its due timers if no hook moved it, and the parallel state's own hooks and timers run only when no region moved.alwaysis checked in the same order, one move at a time. - A target in another region re-enters the parallel state. A rule from
/alive/move/idleto/alive/weapon/cooldownexits all of/aliveand enters it again. - Regions run in name order,
movebeforeweapon, whatever order the config lists them in. Names compare by Unicode code point, so the order is the same in Bun and in Defold. Name regions to match the order you want. pathstays one leaf, the first region's, so code written for a machine without regions keeps working.leaveslists every active leaf in region order: after oneSTART_FIREit is["/alive/move/run", "/alive/weapon/cooldown"].matchesis true for every active state in every region.- A region root can carry
restoreDepthand resumes its last child when the parallel state is entered again. - What throws. A parallel state with
initial,restoreDepthor no child states throws when the machine is defined, naming its path;initialis also a compile error. The root config cannot be parallel: put the regions in a child state.
Read another region in a when
A when receives the running machine as its last argument, so a rule in one region can depend on the state of another. This knight has a move and a posture region, and jumps only while standing:
JUMP: {
to: "/alive/move/jump",
when: (_ctx, _event, machine) => machine.matches("/alive/posture/standing"),
},m.state("/alive/move/idle")
.on("JUMP")
.when((_ctx, _event, machine) => machine.matches("/alive/posture/standing"))
.to("/alive/move/jump");- The view is read-only. It has no
send,stoporctx: the context is the first argument of thewhen. - A
whensees the regions that already moved. Regions take an event in name order, so awheninposturesees wheremovewent for that event, and awheninmoveseespostureas it was. - A
whenthat asks about a group of states, in one region or across several, reads a tag.
Name a group of states with tags
A state has one parent, so a group of states that crosses branches of the tree has no path of its own. A tag names such a group. This knight's roll state, in one region, and its raised shield up, in another, each carry tags: ["invulnerable"], and a hit lands only while neither is active:
HIT: {
when: (_ctx, _event, machine) => !machine.hasTag("invulnerable"),
run: (ctx, event) => {
ctx.health -= event.damage;
},
},m.state("/alive")
.on("HIT")
.when((_ctx, _event, machine) => !machine.hasTag("invulnerable"))
.run((ctx, event) => {
ctx.health -= event.damage;
});- A tag holds while any state that carries it is active. A parent's tag holds while any of its children is active, and a tag in any region of a parallel state counts. Landing from a roll with the shield up leaves the knight invulnerable, which a flag set in
enterand cleared inexitgets wrong. - Tag names are the third type argument of
defineMachine, heredefineMachine<KnightCtx, KnightEvent, KnightTag>()withtype KnightTag = "invulnerable". Atagsentry and ahasTagargument accept only those names, on the instance and on themachineevery callback receives. Without the third argument neither compiles. hasTagonly reads. It answersfalsefor a name no state carries and once the machine is stopped. It builds no table, so anupdatehook can call it every frame.- A tag names a group and nothing else. It carries no rule, hook or timer: behavior the states share goes on a parent state, and one branch of the tree is asked with
matches.
Run to completion, task and stop
A machine handles one event at a time, to completion.
- A
sendduring a step queues. Called from a hook, arun, ataskor a listener, it runs after the current move, everyenterandexitincluded, has finished. - Queued events run in order before the outer
send,updateorstartreturns, sostarthands back a machine that has already handled whatever itsenterhooks sent. stop()exits every active state, deepest first and the root last, and setspathtoundefined. After it,sendandupdatedo nothing.stop()inside a step lets that step finish, then drops any queued events instead of running them.
This level's loading state calls machine.send({ type: "LOADED" }) from its enter hook when the level is cached, and its last state, done, calls machine.stop() from enter:
const m = level.start({ cached: true });
m.path; // "/playing": start ran the queued LOADED before returning
m.send({ type: "QUIT" });
m.path; // undefined: done stopped the machineEngine callbacks: task and finish
Work that finishes later, such as an animation, a proxy load or an HTTP response, belongs in a state's task:
opening: {
task: (ctx, finish) => {
go.animate(ctx.sprite, "tint.w", go.PLAYBACK_ONCE_FORWARD, 0, go.EASING_LINEAR, 0.5, 0, () => {
finish({ type: "OPENED" });
});
},
exit: (ctx) => {
go.cancel_animations(ctx.sprite, "tint.w");
},
on: { OPENED: "/open" },
},m.state("/opening").task((ctx, finish) => {
go.animate(ctx.sprite, "tint.w", go.PLAYBACK_ONCE_FORWARD, 0, go.EASING_LINEAR, 0.5, 0, () => {
finish({ type: "OPENED" });
});
});
m.state("/opening").exit((ctx) => {
go.cancel_animations(ctx.sprite, "tint.w");
});
m.state("/opening").on("OPENED").to("/open");- A
taskruns after the state'senterhook on every entry, and lives as long as that entry. finish(event)is one-shot. Pass it whichever typed event means success or failure.- A late
finishis ignored. If the state was left, re-entered, or the machine was stopped before the callback fires, it moves nothing. - A
taskmay return a cleanup function. The machine calls it once when that entry ends: after the state'sexithook, onstop(), before a re-entry starts the nexttask, and when a hot reload removes the state. A machine that lives during one state returns one. - Several pieces of work are counted with a
WaitGroup; see Wait for something to finish.
Cleanup runs on exit, never after an await
Whatever a state starts, its exit hook stops: an animation, a timer, a pending request. The cleanup a task returns does the same job. Both run on every way out of the state, stop() included, so opening above cancels its fade even when the object is deleted mid-fade.
Never put cleanup after an await in a task or a hook. By the time the awaited work resumes, the state may be gone, and that code cleans up after a state that no longer exists, or never runs at all.
Scripted sequences
sequence from @defold-typescript/types/hsm/async turns an async function into a task. The function receives the context and a signal, and the event it returns is sent to the machine:
task: sequence(async (ctx, signal) => {
msg.post(ctx.title, "enable");
await signal.wait(2);
msg.post(ctx.title, "disable");
await signal.wait(0.5);
return { type: "DONE" };
}),
on: { DONE: "/menu", SKIP: "/menu" },m.state("/playing").task(
sequence(async (ctx, signal) => {
msg.post(ctx.title, "enable");
await signal.wait(2);
msg.post(ctx.title, "disable");
await signal.wait(0.5);
return { type: "DONE" };
}),
);
m.state("/playing").on("DONE").to("/menu");
m.state("/playing").on("SKIP").to("/menu");await signal.wait(seconds)pauses for that long in engine time. It waits ontimer.delay, not onupdate(dt), so it keeps counting while a machine's updates are paused.- Leaving the state cancels a pending
signal.wait, so the code after it never runs:SKIPstops the sequence at its currentwait. An event the sequence returns after the state is left is ignored. - Only
signal.waitis cancelled. Any other promise youawaitcan still resolve after the state is left, and the code after it then runs. Checksignal.aborted, which turnstrueonce the state is left, and return before doing work that belongs to the state, as A group inside a sequence does. - An error thrown inside the sequence leaves the machine where it is and is raised again from a fresh timer callback, so it shows in the engine console.
Watchdog
task and sequence take no timeout option. Put the deadline on the state: an after entry leaves the state when nothing finished in time, and leaving it ignores the late finish and runs the cleanup.
loading: {
task: (ctx, finish) => {
http.request(ctx.url, "GET", (_self, _id, response) => {
finish(response.status === 200 ? { type: "LOADED" } : { type: "FAILED" });
});
},
after: { 5: "/failed" },
on: { LOADED: "/ready", FAILED: "/failed" },
},m.state("/loading").task((ctx, finish) => {
http.request(ctx.url, "GET", (_self, _id, response) => {
finish(response.status === 200 ? { type: "LOADED" } : { type: "FAILED" });
});
});
m.state("/loading").after(5).to("/failed");
m.state("/loading").on("LOADED").to("/ready");
m.state("/loading").on("FAILED").to("/failed");Wait for something to finish
Many states exist to wait: an intro plays to its end, a level loads, every door of a room opens. The library has no final state, so what finishes picks the recipe:
| What finishes | Recipe |
|---|---|
| A chain of child states that run one after another | The last child names the next state; see A chain of child states |
| Several pieces of engine work a state started | A task waits on a waitGroup; see Work that completes |
| Regions with states of their own | always on the parallel state; see Regions with states of their own |
Several pieces of work inside a sequence | The sequence awaits the group; see A group inside a sequence |
A piece that never reports keeps its state waiting, whichever recipe counts it: put a deadline on the state, as the watchdog does. A machine that has finished altogether ends itself with stop() in the enter hook of its last state.
A chain of child states
When the children run one after another, the last one names what comes next. /intro/credits ends the intro by naming /menu, a state outside its parent:
states: {
logo: { after: { 2: "/intro/title" } },
title: { after: { 2: "/intro/credits" } },
credits: { after: { 2: "/menu" } },
},m.state("/intro/logo").after(2).to("/intro/title");
m.state("/intro/title").after(2).to("/intro/credits");
m.state("/intro/credits").after(2).to("/menu");Let the parent decide when the chain should not know what follows it: the next state depends on a condition, or more than one child can end the chain. The last timer then leads to a child that sends an event:
credits: { after: { 2: "/intro/done" } },
done: { enter: (_ctx, machine) => machine.send({ type: "INTRO_DONE" }) },m.state("/intro/credits").after(2).to("/intro/done");
m.state("/intro/done").enter((_ctx, machine) =>
machine.send({ type: "INTRO_DONE" }),
);INTRO_DONE is queued: it runs as soon as the move into done has finished, and bubbles to /intro, whose rule INTRO_DONE: [{ to: "/tutorial", when: (ctx) => ctx.firstRun }, { to: "/menu" }] picks the next state.
Work that completes
Engine work that reports through a callback is counted with a WaitGroup. A task builds the group and hands one group.add() to each engine call, and group.wait finishes with an event once every piece has reported:
task: (ctx, finish) => {
const group = waitGroup();
go.animate(ctx.curtain, "tint.w", go.PLAYBACK_ONCE_FORWARD, 0, go.EASING_LINEAR, 0.5, 0, group.add());
const loaded = group.add();
http.request(ctx.url, "GET", (_self, _id, response) => {
if (response.status === 200) {
loaded();
} else {
finish({ type: "FAILED" });
}
});
group.wait(() => finish({ type: "READY" }));
},m.state("/loading").task((ctx, finish) => {
const group = waitGroup();
go.animate(ctx.curtain, "tint.w", go.PLAYBACK_ONCE_FORWARD, 0, go.EASING_LINEAR, 0.5, 0, group.add());
const loaded = group.add();
http.request(ctx.url, "GET", (_self, _id, response) => {
if (response.status === 200) {
loaded();
} else {
finish({ type: "FAILED" });
}
});
group.wait(() => finish({ type: "READY" }));
});The fade takes group.add() as its callback. The request can fail, so it gets a callback of its own: a response with status 200 reports to the group, and any other status calls finish with FAILED itself.
The number of pieces need not be written in the code. A loop adds one piece per item of a list whose length is known only while the game runs:
const group = waitGroup();
for (const enemy of ctx.enemies) {
go.animate(enemy, "position.y", go.PLAYBACK_ONCE_FORWARD, 0, go.EASING_OUTQUAD, 1, 0, group.add());
}
group.wait(() => finish({ type: "ARRIVED" }));group.wait goes after the loop. With an empty list nothing is pending, so wait calls back at once and the machine is in /fighting when start returns.
Regions with states of their own
When each part has states of its own, make the parts regions of a parallel state and put an always rule on that state. Its when asks matches for the last state of each region:
setup: {
type: "parallel",
always: {
to: "/fight",
when: (_ctx, machine) => machine.matches(DOORS_OPEN) && machine.matches(MUSIC_READY),
},
states: {
doors: {
initial: "/setup/doors/opening",
states: { opening: { on: { OPENED: DOORS_OPEN } }, open: {} },
},
music: {
initial: "/setup/music/fading",
states: { fading: { on: { FADED: MUSIC_READY } }, ready: {} },
},
},
},const m = buildMachine<object, RaidEvent>()({
initial: "/setup",
states: {
setup: {
type: "parallel",
states: {
doors: {
initial: "/setup/doors/opening",
states: { opening: {}, open: {} },
},
music: {
initial: "/setup/music/fading",
states: { fading: {}, ready: {} },
},
},
},
fight: {},
},
});
m.state("/setup")
.always()
.when((_ctx, machine) => machine.matches(DOORS_OPEN) && machine.matches(MUSIC_READY))
.to("/fight");
m.state("/setup/doors/opening").on("OPENED").to(DOORS_OPEN);
m.state("/setup/music/fading").on("FADED").to(MUSIC_READY);OPENED and FADED can arrive in either order. The move that brings the second region to its last state is followed by the move to /fight, in the same send.
- Hold each last state's path in a constant, as in
const DOORS_OPEN = "/setup/doors/open". One constant is the region'stoand the path the join asks about, and each fails to compile when it names no state. - The join is asked after the regions. A region's own
alwaysrules run before the parallel state's rule, so itswhensees each region where it came to rest. - The active states already hold the answer. A counter in the context, raised by each region as it finishes, repeats what
matchesreads and has to be reset on every entry.
A group inside a sequence
A sequence waits on a group through a promise around wait:
task: sequence(async (ctx, signal) => {
const group = waitGroup();
http.request(ctx.url, "GET", group.add());
go.animate(ctx.logo, "tint.w", go.PLAYBACK_ONCE_FORWARD, 1, go.EASING_LINEAR, 0.5, 0, group.add());
await new Promise<void>((resolve) => group.wait(() => resolve()));
if (signal.aborted) return;
msg.post(ctx.logo, "disable");
return { type: "READY" };
}),m.state("/booting").task(
sequence(async (ctx, signal) => {
const group = waitGroup();
http.request(ctx.url, "GET", group.add());
go.animate(ctx.logo, "tint.w", go.PLAYBACK_ONCE_FORWARD, 1, go.EASING_LINEAR, 0.5, 0, group.add());
await new Promise<void>((resolve) => group.wait(() => resolve()));
if (signal.aborted) return;
msg.post(ctx.logo, "disable");
return { type: "READY" };
}),
);- Leaving
/bootingdoes not cancel that promise. It resolves when the last piece reports, so thesignal.abortedcheck returns before the logo is hidden for a state that is no longer active. waittakes an arrow function that callsresolve.group.wait(resolve)passes the type check and fails the build withUnable to convert function with a 'this' parameter to function 'callback' with no 'this'.
Write a machine as statements
hsm/builder writes a machine as a skeleton plus one statement per rule, for code that reads as "in /off, on TOGGLE, go to /on". This is the lamp from States and paths:
import { buildMachine } from "@defold-typescript/types/hsm/builder";
type LampEvent = { type: "TOGGLE" } | { type: "DIM" };
const m = buildMachine<object, LampEvent>()({
initial: "/off",
states: {
off: {},
on: { initial: "/on/bright", states: { bright: {}, dim: {} } },
},
});
m.state("/off").on("TOGGLE").to("/on");
m.state("/on").on("TOGGLE").to("/off");
m.state("/on/bright").on("DIM").to("/on/dim");
m.state("/on/dim").on("DIM").to("/on/bright");
export const lamp = m.build();- The skeleton holds structure only: the root's
initial,states,restoreDepthandprivateCtx, and on each stateinitial,states,typeandrestoreDepth, checked as in a config. It fixes the paths every statement takes, so an unknown path or event fails to compile, and so does a behavior key such asonorenterin the skeleton. - Each
on,after,everyandalwayscall adds one entry, in call order. A state'son,everyandalwaysentries are tried in that order:on("HIT").when(fatal).to("/dead")thenon("HIT").run(damage)is the listHIT: [{ when, to }, { run }]. Itsaftertimers are tried in delay order, call order breaking ties. Anonrule ends withto,runorignore, a timer withtoorrun, aneverywithrunand analwayswithto;runtakes several functions, run in order.ignore()takes the event with nothing to do, so no parent's rule sees it. enter,exit,update,task,unhandledandtagsset the slot of the same name; a secondenter,exit,update,taskorunhandledon one state throws.m.rootis the root's builder: its rules take an event no state below takes.build()writes the statements onto the skeleton's own state objects, in list form, and passes the skeleton todefineMachine. It throws, naming the state, on a rule left without its ending; after it, every statement and a secondbuild()throw.- Hot reload takes the key as
defineMachinedoes: withbuildMachine<object, LampEvent>("lamp"), a reload'sbuild()returns the same machine, and its live instances take the new rules.
Every snippet on this page that configures a machine has a Builder tab beside its Config tab, which shows the same machine as statements.
Define a machine in a plain module
Put each machine definition in a plain module, a file with no defineScript export. A plain module compiles to .lua, which any script can require; a file that exports a defineScript factory compiles to a .ts.script component, which other files cannot import. The door's script below imports doorMachine and its message mapper doorEvents from ./door-machine.
One instance per object, on self
start(ctx) creates an independent instance from the definition. Create it in init so it lands on self, one per game object, then tick it from update(dt) and stop it in final:
export default defineScript({
init() {
return { door: doorMachine.start({ sprite: msg.url("#sprite"), opens: 0 }) };
},
update(self, dt) {
self.door.update(dt);
},
on_message(self, message_id, message, sender) {
const event = doorEvents.toEvent(message_id, message, sender);
if (event !== undefined) {
self.door.send(event);
}
},
final(self) {
self.door.stop();
},
});self.door.matches("/open"),self.door.pathandself.door.ctxread the current state from any callback.- A machine sees only its
ctxand its events, neverself, so script data a hook needs goes intoctxatstart. - A module-level instance,
const door = doorMachine.start(...)at the top of a script file, is shared by every object that runs the script; see Where script state lives. - Here
selftakes its type from whatinitreturns. For a namedSelftype, apropertiesblock, or a machine that starts later, see Typeself.
Ask whether an event would be taken
can(event) answers whether a rule of some active state would take the event if it were sent now. Use it for a button that should look disabled, or in a script that picks between two events. Pass the event as send would get it, payload included: this enemy's only HIT rule moves to /dead when ctx.health <= event.damage, so two hits get different answers.
const e = enemy.start({ health: 3 });
e.can({ type: "HIT", damage: 3 }); // true: this hit is fatal
e.can({ type: "HIT", damage: 1 }); // false: the only rule's `when` fails
// @ts-expect-error a HIT carries its damage
e.can({ type: "HIT" });- It checks
when. A rule counts when itswhenis missing or passes. - A rule with no
tocounts.canasks whether a rule would take the event, not whether the state would change. - Nothing runs. No hook,
unhandledincluded, norunand noonMoveoronUnhandledlistener is called, and the event is not queued. - Inside a hook it answers for the states active at that moment. A state's
enterhook already counts that state. A stopped machine answersfalse. - A
whencannot call it. The view awhenreceives has nocan.
Listen for unhandled events
onUnhandled(listener) calls the listener with each event no rule took, for logging or a tool. A reaction the machine owns is an unhandled hook instead. This door's closed state has a rule for OPEN and the empty rule KNOCK: {}:
const off = m.onUnhandled((event) => {
print(`door ignored ${event.type} in ${m.path}`);
});
m.send({ type: "CLOSE" }); // prints: door ignored CLOSE in /closed
m.send({ type: "KNOCK" }); // nothing: the empty rule takes KNOCK- It reports the events
cananswersfalsefor. An event whose everywhenfails is one of them, and an event an empty rule takes is not. - A
sendfrom a hook, arunor afinishcounts. The listener hears every event the machine processes, not only the ones a script sends. - The listener runs inside the step, after the states'
unhandledhooks.pathandleavesshow the states the event found. - A stopped machine reports nothing: not a
sendafterstop(), not an event still queued whenstop()ends the step, not a latefinish. - Each call adds a listener. The function it returns,
offabove, removes it.
Restart a machine
A stopped instance does not start again. To restart, stop the instance, start a new one from the same definition, and store it where the old one was: self.door.stop(), then self.door = startDoor(), where startDoor is the function init calls too. The cheat sheet has the snippet.
startentersinitialwith the context it is given: a new object for a clean start, or the old instance'sctxto keep its fields. To enter other states, pass saved paths.- Restart from a script callback, not from a hook. Inside a hook,
stop()waits for the step to end, so astarton the next line runs the new instance'senterhooks before the old instance'sexithooks. - Listeners stay with the old instance. Call
onMove,onUnhandledandinspectagain on the new one. on_reloadsuits a restart; see Restart on a hot reload.- To restart one state and keep the instance, name the state as its own target.
Several machines
Parts of one object that each have a state are compound or parallel states of one machine. A second machine is for a second thing: another game object, or something that has a life of its own. An instance is a plain object that fits in a context or on self, so the library has no spawn call and no parent or child helper. How the two machines relate picks the recipe:
| The machines | Recipe |
|---|---|
| On separate game objects | Each script runs its own machine, and they post messages; see Separate objects talk with messages |
| Two in one script, where one reads the other | The reader holds the other instance in its context; see Two machines in one script |
| One that exists only while a state of another is active | The state's task starts it and the cleanup stops it; see A machine that lives during one state |
Separate objects talk with messages
Machines on separate game objects never hold each other. Each script runs its own machine, and the two talk the way any two scripts do, with msg.post. A boss wakes its minions from the enter hook of /shielded, which runs inside start, and drops its shield once the last one is down:
enter: (ctx) => {
for (const minion of ctx.minions) {
msg.post(minion, "minion_wake");
}
},m.state("/shielded").enter((ctx) => {
for (const minion of ctx.minions) {
msg.post(minion, "minion_wake");
}
});A minion answers event.sender, the boss's script, and keeps that url:
minion_wake: {
to: "/awake",
run: (ctx, event) => {
ctx.owner = event.sender;
msg.post(event.sender, "minion_ready");
},
},m.state("/asleep")
.on("minion_wake")
.to("/awake")
.run((ctx, event) => {
ctx.owner = event.sender;
msg.post(event.sender, "minion_ready");
});- A minion out of
hptells its owner. Theenterhook of/downpostsminion_downtoctx.owner. - The boss counts.
minion_readyadds one toctx.alive, andminion_downtakes one off or, for the last minion, moves to/exposed. - Neither module imports the other. The boss knows its minions by the ids its script got from
factory.createand passed tostart, and a minion knows its owner by the sender of the message that woke it, so the same minion serves any object that wakes it. CustomMessagesis global. The three messages are declared once, in the boss's module, and both modules see them; see The message bridge.- The minion's script has the shape of the door's, and sends
HITitself when something hurts the minion.
Two machines in one script
Two machines in one script are two instances on self. When a rule of one depends on the state of the other, the first holds the second in its context and asks it in a when. A hero whose context holds round, typed ReturnType<typeof roundMachine.start>, jumps only while the round is being played:
JUMP: { to: "/airborne", when: (ctx) => ctx.round.matches("/playing") },m.state("/grounded")
.on("JUMP")
.when((ctx) => ctx.round.matches("/playing"))
.to("/airborne");The script starts the round first, because the hero's context needs it:
init() {
const round = roundMachine.start({});
return { round, hero: heroMachine.start({ round }) };
},
update(self, dt) {
self.round.update(dt);
self.hero.update(dt);
},
final(self) {
self.hero.stop();
self.round.stop();
},- Tick the machine that is read first.
updateticks the round, then the hero, so a rule of the hero sees where the round is in this frame. - Stop them in the opposite order.
finalstops the hero while the round it reads is still running. - A mistyped path fails to compile. The type of
roundcarries the round's paths, soctx.round.matches("/playng")is an error where it is written.
A machine that lives during one state
A machine that exists only while one state of another is active is started in that state's task and stopped in the cleanup the task returns. A brawler counts a combo while it fights. The combo is a machine of its own: every hit gives it one more second, and it ends when a second passes with no hit.
task: (ctx, finish) => {
const combo = comboMachine.start({
hits: 0,
done: (hits) => finish({ type: "COMBO_ENDED", hits }),
});
ctx.combo = combo;
return () => {
combo.stop();
ctx.combo = undefined;
};
},
update: (ctx, dt) => {
ctx.combo?.update(dt);
return undefined;
},m.state("/fighting").task((ctx, finish) => {
const combo = comboMachine.start({
hits: 0,
done: (hits) => finish({ type: "COMBO_ENDED", hits }),
});
ctx.combo = combo;
return () => {
combo.stop();
ctx.combo = undefined;
};
});
m.state("/fighting").update((ctx, dt) => {
ctx.combo?.update(dt);
return undefined;
});- Start in the
task. Every entry of/fightingstarts a new combo and keeps it inctx.combo. - Tick in
update. The hook passes itsdton, because a machine nobody ticks is frozen. - Send from a rule.
PUNCH: { run: (ctx) => ctx.combo?.send({ type: "HIT" }) }has noto: the brawler stays where it is and the combo gets aHIT, whose rule names its own state to start the second over. - Report through a callback. The combo's last state calls
ctx.done, which calls thefinishof the brawler'stask. The brawler takesCOMBO_ENDEDonce its own step has ended. - Stop in the cleanup, which runs on every way out of
/fighting, so no combo outlives the fight.
The callback sits in the combo's context because a machine sees only its context and its events. The combo knows nothing about the brawler, and any machine can start one.
Hot reload
Hot reload lets you edit a machine while the game runs and see the change without restarting. Give defineMachine a key, a name for this definition, as in defineMachine<EnemyCtx, EnemyEvent>("enemy").
When watch --hot-reload or reload pushes an edit, Defold runs the changed file again, and every script that already imported it keeps the first copy. With a key, defineMachine finds the machine it built the first time, in a table the hsm library keeps across reloads, and puts the new states into that same object, so every running instance sees the edit. Without a key the edited call builds a new machine that no script holds, and the instances already running keep the old states until you restart.
Call a keyed defineMachine once, at the top level of a module, so it runs once each time the file loads. Inside init it runs once per object: each new enemy redefines "enemy", every enemy already alive switches to that definition, and values its hooks took from that init replace everyone's.
What happens after a reload
- The file runs again, and
defineMachine("enemy")puts the new states into the existing machine. If the new config has a mistake, it throws and the old states stay in use. - The running instances do not change yet:
pathstill reads the old state, andcanstill answers from the old rules. - On its next
sendorupdate, each instance sees the new definition and switches to it. Becauseupdateruns every frame, that is the next frame. The script needs noon_reloadfor this.
What each instance keeps
An instance always keeps its ctx. What happens to its current state depends on the edit:
| After the edit, the current state… | The instance… |
|---|---|
| still exists | stays in it and runs no enter or exit hook. The edited rules, when checks and hooks apply from now on. |
| still exists, but now has child states | enters its initial child, and that child's initial, and so on, running their enter hooks. |
| was removed | moves to the closest parent state that still exists and enters that parent's initial chain, running those enter hooks. The removed states run no exit hook, because their code is gone, but a cleanup their task returned still runs, deepest state first. |
| is a parallel state that gained a region | keeps its other regions as they are and enters only the new one. |
| was a parallel state and is now compound | keeps its first region in name order and drops the others like removed states. |
- A state that stays keeps its clock, and which of its timers fired: by entry for a list that holds a delay function, so each mark stays on its own timer when the delays read differently after the reload, and by position in delay order for every other form. The delay functions of its timers and
everyentries are read again, and eacheveryentry next runs at the first multiple of its delay above that clock. - States are matched by path, so renaming
chasetohuntcounts as removing/chase. - A state with
restoreDepthkeeps its remembered children the same way. If the edit removed a remembered child, the next entry usesinitialat that level. - A change of state is reported.
onMovelisteners get the move with the cause"reload", and the debug inspector prints it. - The key names the definition, not an object. Twenty enemies that start
enemyMachineininitare twenty instances of one machine: a reload changes the machine once, and each instance switches on its own nextupdate, following the table for its own state. - Different machines need different keys. If doors also used
"enemy", each reload of one file would replace the other machine's states.
Restart on a hot reload
A reload keeps each instance in its current state when that state still exists, so an edited enter hook waits for the next entry and the instance keeps the ctx it started with. To start over instead, restart the machine in the script's on_reload. The two work side by side, and which one runs depends on the file you edit:
| You edit | What runs | The instance… |
|---|---|---|
| the machine's module, defined with a key | the switch described above, on the next send or update | stays in its state with its ctx, under the new rules. |
| the machine's module, defined without a key | nothing | keeps the old states, and so does an instance a later restart starts. |
the script file, with a restart in on_reload | stop(), then start | is replaced by a new one at initial, with the context the script builds. |
- A restart starts the newest definition. With a key,
startuses the states the definition holds when it is called. - Editing only the machine's module restarts nothing. Defold calls
on_reloadonly on a script whose own file was reloaded, and a reload does not runinitagain. - Every object that runs the script restarts.
on_reloadruns once per object, so 20 enemies all go back toinitial. - Build the starting context in the script file. A reloaded script still gets the first copy of every module it imports, so a context factory exported from the machine's module stays the old one.
Save and load
A saved game resumes each object in the state it was in: an opened chest stays open. Where the fact lives picks the way: in data the game already saves, or only in the machine's current state.
Route from saved data
When the saved data tells the state, such as a flag or a count, start the machine as usual and let an always list on its first state pick where to go:
restore: {
always: [{ to: "/open", when: (ctx) => ctx.opened }, { to: "/closed" }],
},m.state("/restore").always().when((ctx) => ctx.opened).to("/open");
m.state("/restore").always().to("/closed");The enter hook of open sets ctx.opened, and the game saves it with the rest of its data and passes it back in the context.
Start at saved paths
When the state itself is the fact, as for a door, a chest or a switch, save the active paths and start the machine at them. This chest plays its animation when open is entered:
open: {
enter: (ctx) => {
sprite.play_flipbook(ctx.sprite, "open");
},
},m.state("/open").enter((ctx) => {
sprite.play_flipbook(ctx.sprite, "open");
});start takes a list of state paths as its second argument. The script loads the list in init and saves leaves in final:
init() {
const save = sys.load(SAVE_FILE) as ChestSave;
return { chest: chestMachine.start({ sprite: msg.url("#sprite") }, save.at) };
},
final(self) {
sys.save(SAVE_FILE, { at: self.chest.leaves });
self.chest.stop();
},ChestSave types at as an optional list of the machine's paths. sys.load returns an empty table when there is no save yet, so save.at is undefined and the chest starts at initial.
- The entry is an ordinary one.
privateCtxruns,enterhooks run outermost first, tasks start, delay functions are read andalwaysrules are checked. The opened chest plays its animation because itsenterruns. - A path may name a state with children. Below it the entry goes through
initial, as does a level or region no path names. - A path the machine lacks falls back to its closest parent that exists, as a hot reload treats a removed state. A save made before an edit still loads.
- Of two paths that cannot be active together, the first in the list wins.
- Only the active states are part of a start position. Every clock starts at zero, no state remembers a child for
restoreDepth, and ataskstarts again. The context is the game's own table to save. leavesis the same array on every read, updated in place.sys.savewrites it at the call, and a table kept for later takes a copy,[...self.chest.leaves].
Private fields with privateCtx
Some of a machine's data belongs to the machine alone: a counter, a heat level, a list it builds up. The root config takes one optional key for such fields: privateCtx, a function that returns them. Every hook, when, run, task and update sees the fields beside Ctx, while start takes Ctx alone and the instance it returns shows Ctx alone in its ctx.
Inferred. For a few fields, write them inline and let TypeScript infer their types:
privateCtx: () => ({ heat: 0, targets: [] as Hash[] }),const m = buildMachine<{ readonly fireRate: number }, TurretEvent>("turret")({
privateCtx: () => ({ heat: 0, targets: [] as Hash[] }),
initial: "/idle",
states: { idle: {}, firing: {} },
});Add as where the inferred type is wrong: an empty array is never[] until it reads [] as Hash[], and a field holding one of several strings is any string until it reads "cool" as "cool" | "hot".
A named type. For more fields, or when a helper outside the config needs the whole context, declare the fields as an interface and make it the factory's return type:
privateCtx: (): TurretPrivate => ({ heat: 0, mode: "cool" }),const m = buildMachine<TurretOptions, TurretEvent>("turret")({
privateCtx: (): TurretPrivate => ({ heat: 0, mode: "cool" }),
initial: "/idle",
states: { idle: {}, firing: {}, cooling: {} },
});The fields need no as, a misspelled or unknown field is a compile error, and a helper types the whole context as TurretOptions & TurretPrivate.
Warning
satisfies TurretPrivate does not do the same job. It checks the object but keeps its narrow types, so an empty array stays never[] and nothing can be pushed to it:
privateCtx: () => ({ heat: 0, targets: [] }) satisfies TurretPrivate,const m = buildMachine<{ readonly fireRate: number }, { type: "SPOTTED" }>()({
privateCtx: () => ({ heat: 0, targets: [] }) satisfies TurretPrivate,
initial: "/idle",
states: { idle: {} },
});From the starting context. The factory receives the object passed to start, so a private field can start from a field of Ctx:
privateCtx: (ctx: TurretOptions) => ({ heat: ctx.startHeat }),const m = buildMachine<TurretOptions, TurretEvent>("turret")({
privateCtx: (ctx: TurretOptions) => ({ heat: ctx.startHeat }),
initial: "/idle",
states: { idle: {}, firing: {} },
});- It runs once per
start, before the root'senterhook, so the fields are there when the first hook runs. - Every instance gets fresh fields of its own. A value written straight into the config would be one array or table shared by every instance.
- It receives the object passed to
start, typedCtx, and adds the fields to that object, which stays the instance'sctx. A factory that readsctxgives it a type: write(ctx: TurretOptions) => ..., not(ctx) => ...: without the type, TypeScript can type a hook or asequencetask before it knows the private fields, and that hook reports the field as missing. - A restart builds them fresh.
start(old.ctx)keeps the public fields and builds the private ones again; see Restart a machine. - A hot reload adds fields and keeps values. A reload under the machine's key adds the fields a new
privateCtxintroduces and leaves every field that already holds a value alone. - A private field may not share a name with a field of
Ctx. Such a config fails to compile. - The fields are hidden by type only. At run time
ctxis one table, and hooks, theviewcommand and a debugger see every field.
Performance
The budget is 200 game objects, each running its own instance of one three-level machine, for under 0.5 ms of update and send per frame in the stock engine, with neither call building a table. A bench in the repository measures it: every enemy ticks its machine each frame through after timers and an update hook and sends one event every 20 frames, over 300 frames that sample the heap around each call and 300 that time each call.
| Avg ms per frame | Worst frame ms | Allocating calls (update / send) | Heap KB (update / send) | Engine | System | Date |
|---|---|---|---|---|---|---|
| 0.05 | 0.10 | 3 of 60,000 / 6 of 3,000 | 2.2 / 7.0 | 1.13.2 | macOS, arm64 | 2026-10-03 |
The few allocating calls are the Lua VM's own one-time work the first time a path runs (a JIT trace, a deeper call stack), not the machine. Reproduce it from a clone of the repository with Java and a display:
bun run --cwd packages/api-probe bench:hsmupdate and send build nothing, but the event you pass is a table: an event literal written at the send call builds a new one on every call, and so does toEvent from the message bridge. On a hot path, hoist a constant event to the top of the module and send that:
const SPOT = { type: "SPOT" } as const;
const m = guard.start({ seen: 0 });
m.send(SPOT); // the same table on every call
m.send({ type: "LOSE" }); // a new table on every callTypes
defineMachinetakes two calls.defineMachine<Ctx, E>()fixes the context and event types and takes the optional hot reload key. The second call takes the config, which has to be inferred: its literal shape is where the state paths come from.- Events are objects with a string
type, plus any payload fields.onaccepts only thetypevalues ofEas keys, and eachwhenandrunsees the variant its key names. - Tags are the third type argument; see Name a group of states with tags.
- A state takes only the fields of a state. A field no state has, such as a misspelled
entror an extralabel, fails to compile, also on a state built ahead of the config in a constant or by a helper. startreturns aMachineInstance<Ctx, E, P, Tag>, wherePis the union of the machine's state paths.pathcan beundefined, so a lookup table keyed by path is indexed only after a check. Name the type withReturnType<typeof doorMachine.start>; see Read types off the machine.- The second argument of
startisreadonly P[], so a copy ofleavesfits, and a list loaded asstring[]takes a cast where it is loaded; see Start at saved paths. MessageEvent<K>andmessageEventsturn Defold messages into machine events; see The message bridge.
A when reads its arguments. ctx is Readonly<Ctx> in every when, under on, always and after, and in a delay function of after and every, so the write a when must not make fails to compile:
when: (ctx, event) => {
// @ts-expect-error -- a `when` cannot assign to a field of `ctx`
ctx.health -= event.damage;
return ctx.health <= event.damage;
},m.state("/alive")
.on("HIT")
.when((ctx, event) => {
// @ts-expect-error -- a `when` cannot assign to a field of `ctx`
ctx.health -= event.damage;
return ctx.health <= event.damage;
})
.to("/dead")
.run((ctx, event) => {
ctx.health -= event.damage;
});- The event is read-only in a
when, arun, theunhandledhook and theonMoveandonUnhandledlisteners, so an event kept in a constant is the same on everysend. - The check is one level deep: a list or table held in a field can still be changed.
- A helper declared outside the config with ordinary parameter types still fits, and its own writes are not checked. The one exception is a helper typed with a context class that has a private or protected member: its parameter takes
Readonly<...>of the class, as in(ctx: Readonly<Tank>) => ctx.hp > 0.
A bad path is an error where it is written. An initial, a target (on, to, after, always) and the path an update hook returns accept only the machine's full paths, and an on key accepts only an event type. A typo, a bare name such as "idle" included, fails to compile on that property, and the editor suggests the paths and event types as you type:
// @ts-expect-error -- "/nowhere" is not one of the machine's paths
GO: "/nowhere",// @ts-expect-error -- "/nowhere" is not one of the machine's paths
m.state("/idle").on("GO").to("/nowhere");A path below a state with no child states fails to compile too, and so do initial and restoreDepth on such a state:
// @ts-expect-error -- "/done" has no child states, so no path goes below it
GO: "/done/deeper",// @ts-expect-error -- "/done" has no child states, so no path goes below it
m.state("/idle").on("GO").to("/done/deeper");A callback's machine knows the machine's paths. In a hook, a when, a run and a task, path, leaves and matches() take the machine's paths, and so does onMove on the machine of a hook, a run and a task. A variable typed string does not fit matches() there: give it a union of the paths it can hold, such as "/off" | "/on".
Two cases need care:
- A hook declared outside the config. An
updatehook returns one of the machine's paths orundefined; a plainstringdoes not compile. TypeScript widens a function's single returned path tostring, so such a hook needsas const:const land = () => "/grounded" as const. - A state that holds only callbacks. In a callback,
matches()accepts any path below a state that holds nothing but callbacks with unannotated parameters, and below a parent whose child states are all like that. Anafteroreverylist with such a callback in it counts as one. Targets in the config are still checked there, but the editor does not suggest the children of such a parent. Annotate the parameters of one hook of the state, as inenter: (ctx: LampCtx) => { ... }, or of every callback in the list, andmatches()checks those paths.
StatePath<C> lists a config's paths, each with its leading /. Paths are spelled out four levels deep; below that, any string under a fourth-level path is accepted. Here game is a config object written as const:
// "/menu" | "/playing" | "/playing/running" | "/playing/paused"
type GamePath = StatePath<typeof game>;
const resume: GamePath = "/playing/running";
// @ts-expect-error -- "/playing/over" is not one of the paths
const over: GamePath = "/playing/over";
// @ts-expect-error -- a path without the leading "/" is not a path
const bare: GamePath = "playing";The message bridge
Defold delivers a message as a hashed message_id, a payload table and the sender's URL. messageEvents(ids) turns the ones you list into typed events { type: id, ...payload, sender }.
- The payload types are the ones already declared through
BuiltinMessagesandCustomMessages, so a payload is declared once. MessageEvent<K>is that event's type, for the machine's event union, and carriessender: Url.toEvent(message_id, message, sender)takes theon_messageparameters of bothdefineScriptanddefineGuiScriptand returnsundefinedfor any id you did not list.- A payload field named
typeorsendernever overrides the event's own. - Build the mapper once at module scope: it hashes the ids when it is created.
A when or run reads event.sender to answer whoever sent the message. This lift takes MessageEvent<"call_lift">:
call_lift: {
run: (ctx, event) => {
ctx.floor = event.floor;
msg.post(event.sender, "lift_arrived", { floor: ctx.floor });
},
},m.state("/waiting")
.on("call_lift")
.run((ctx, event) => {
ctx.floor = event.floor;
msg.post(event.sender, "lift_arrived", { floor: ctx.floor });
});A script that already dispatches with onMessage (see Messages) has narrowed payloads in hand and can send them directly, with no mapper. An event built by hand for a MessageEvent union includes sender, which the onMessage handler receives. For two objects whose machines message each other, see Separate objects talk with messages.
Events from an addon
An addon that sends messages to your script needs no adapter. Declare its messages once in CustomMessages, then list the ones the machine handles in messageEvents. This works when the addon builds each id as hash("<name>") for the name you declare, so check the addon's source for how it makes its ids.
Monarch tells every script registered with monarch.add_listener when a screen starts or finishes showing or hiding, and when it fails to show. Its SCREEN_TRANSITION_* constants are hash("monarch_screen_transition_in_started") and so on, so the five messages are declared by those names, beside one of the game's own:
declare global {
interface CustomMessages {
monarch_screen_transition_in_started: { screen: Hash; previous_screen?: Hash };
monarch_screen_transition_in_finished: { screen: Hash; previous_screen?: Hash };
monarch_screen_transition_out_started: { screen: Hash; next_screen?: Hash };
monarch_screen_transition_out_finished: { screen: Hash; next_screen?: Hash };
monarch_screen_transition_failed: { screen: Hash };
game_over: { score: number };
}
}previous_screenisundefinedwhen the stack was empty, andnext_screenon abackpast the first screen.- Register the script with
monarch.add_listener()ininitand remove it withmonarch.remove_listener()infinal. - One mapper covers Monarch's messages and your own.
- Collection proxies need no adapter:
proxy_loaded,proxy_ready,proxy_errorandproxy_unloadedare Defold messages, so list them inmessageEvents.
Debug a machine
To run a machine away from the game, with its source on screen and its active states highlighted, open its file with view.
inspect(instance, label) from @defold-typescript/types/hsm/debug logs every move a machine makes and draws its current path over a game object. Call it once after start, keep the inspector it returns on self, and call its draw from update:
init() {
const door = doorMachine.start({ sprite: msg.url("#sprite"), opens: 0 });
return { door, inspector: inspect(door, "door") };
},
update(self, dt) {
self.door.update(dt);
self.inspector.draw(".");
},inspect prints one line when it is called, then one line for each move and one for an event no active state took:
hsm door frame 0: inspecting [/closed]
hsm door frame 120: /closed -> /opening (trigger_response: /closed, 0) [/opening]
hsm door frame 150: /opening -> /open (OPENED: /opening, 0) [/open]
hsm door frame 200: unhandled (trigger_response) [/open]
hsm door frame 330: /open -> /closed (after: /open, 3) [/closed]| Part of a line | Meaning |
|---|---|
frame 120 | Counts draw calls, so it tracks update when you draw every frame. |
/closed -> /opening | The old and new leaf paths. After stop() the new path reads (stopped). |
(trigger_response: /closed, 0) | The event's type, or the cause when no event moved the machine: after, update, always, stop or reload. Then the path of the state whose rule made the move, empty for the root, and that rule's key. |
[/opening] | Every active leaf after the move, joined by , , so a parallel machine's line names each region's leaf. Empty after stop(). |
- The rule's key is the entry's index in an
onoralwayslist (0for a single rule), the delay of anafterrecord entry, or the index of anafterlist entry. Anupdatemove names the state alone;stopandreloadname neither. - An
unhandledline carries the event'stypeand the active leaves. It prints once per type until the machine's next move, so an event sent every frame does not flood the console. - A label already used by another
inspectcall gets the next ordinal no other call has used,enemy#2,enemy#3, in both the console lines and the drawn text. - Names are escaped in a console line. A backslash escapes each
\,[,],(,),,,>and:inside the label, a path or the event'stype, and a line break reads\n(a carriage return\r), so every line splits back into the same parts. The drawn text shows the names as they are. draw(target)postsdraw_debug_textto@render:with the label and the active leaves joined by,, 40 units above the target's world position.- In a release build, where
sys.get_engine_info().is_debugisfalse,inspectregisters nothing anddrawdoes nothing, so the calls can stay in shipped code.
inspect is built on onMove(listener) and onUnhandled(listener), which every instance has. The onMove listener receives the old leaf path, the new one (undefined after stop()), the cause and the event (undefined unless the cause is event), after the move's enter hooks have run. It is not called for the first entry at start or for a rule with no to. Each call adds a listener and returns a function that removes it.
Test a machine with Bun
@defold-typescript/types/hsm and its sub-modules also run under Bun, so a machine in a plain module can be tested with bun test, with no Defold engine and no mock of the import. A test that imports only bun:test and game code sits next to its module and starts with /// <reference types="bun-types/test" />, and one that needs Bun's runtime goes in src/test/ (Test with Bun). A test imports the machine from its module, or defines one itself:
/// <reference types="bun-types/test" />
import { expect, test } from "bun:test";
import { defineMachine } from "@defold-typescript/types/hsm";
const lamp = defineMachine<{ presses: number }, { type: "PRESS" }>()({
initial: "/off",
states: {
off: { on: { PRESS: "/on" } },
on: {
enter: (ctx) => {
ctx.presses += 1;
},
on: { PRESS: "/off" },
},
},
});
test("a press turns the lamp on", () => {
const instance = lamp.start({ presses: 0 });
instance.send({ type: "PRESS" });
expect(instance.path).toBe("/on");
expect(instance.ctx.presses).toBe(1);
});The core module needs nothing from the engine. A few sub-modules call engine functions, which a test defines on globalThis before it uses them: hsm/defold's messageEvents calls hash, wait inside an hsm/async sequence calls timer.delay, and hsm/debug's inspect calls sys.get_engine_info and msg.post.
Animation states with one-shots
A character has three kinds of animation:
| Kind | Example | Rule |
|---|---|---|
| Looping | idle, run | Can be left at any time. |
| One-shot | jump | Must finish before the next animation starts. |
| In-between | crouching down, standing up | Plays on the way from one posture to the other and must not be skipped. |
Defold's Finite State Machines example drives a knight this way with a table of legal transitions and a path search. Here the tree does that job: the only rules that leave one posture lead to its in-between state, so that animation cannot be skipped. A one-shot is a task, and ends in a pick state that decides what comes next:
jump: {
enter: noJump,
task: once("jump"),
on: { DONE: "/standing/pick" },
},
pick: {
always: [
{ to: "/to_crouch", when: (ctx) => ctx.crouch },
{ to: "/standing/jump", when: (ctx) => ctx.jump },
{ to: "/standing/free/run", when: (ctx) => ctx.run },
{ to: "/standing/free/idle" },
],
},const jump = m.state("/standing/jump");
jump.enter(noJump);
jump.task(once("jump"));
jump.on("DONE").to("/standing/pick");
const pick = m.state("/standing/pick");
pick.always().when((ctx) => ctx.crouch).to("/to_crouch");
pick.always().when((ctx) => ctx.jump).to("/standing/jump");
pick.always().when((ctx) => ctx.run).to("/standing/free/run");
pick.always().to("/standing/free/idle");The script writes what the player wants into knight.ctx.run and knight.ctx.crouch, then sends INTENT, and sends JUMP when the jump key is pressed. The machine decides when to act on it:
- A looping state plays on
enter, as inenter: loop("idle"), whereloopreturns a hook that callssprite.play_flipbook. It can be left at any time, so it needs notask. - A one-shot is a
task.once("jump")returns ataskthat plays the flipbook and callsfinishfrom its completion callback; the state has noINTENTrule, so a new request waits in the context. Set the flipbook's playback to Once Forward in the atlas: a looping flipbook never completes, so its callback never runs. - An in-between state is the only way across. No rule leads from a standing state to a crouching one, so
to_crouchalways plays, whatever was asked for. A new posture adds its in-between state and the rules that lead to it. picksettles on the latest request. Each one-shot ends in apickstate, whosealwaysrules read the context and choose, in order: the other posture, a waiting jump, run, idle.- A trigger during a one-shot is kept.
JUMPonstandingand onto_standinghas arunand noto: it setsctx.jumpand the state stays. The looping states takeJUMPfirst, so a jump from one of them starts at once, andcrouchinghas noJUMPrule, so the knight cannot jump while crouched.jumpandto_crouchclearctx.jumponenter, so a kept jump plays once and crouching down drops it. - An unchanged request restarts nothing. When no rule's
whenpasses, the event is dropped and the flipbook keeps playing, so the script can sendINTENTon every input.
Migrate a script
The platformer example moved its player onto one machine, and src/player-machine.ts is the whole of it. Before, the player's state lived in flags that every frame re-read to pick an animation, and the jump checked a flag of its own:
function update_animations(self: PlayerSelf): void {
// Make sure the player character faces the right way.
sprite.set_hflip("#sprite", self.facing_direction < 0);
if (self.ground_contact) {
if (self.velocity.x === 0) {
play_animation(self, anim_idle);
} else {
play_animation(self, anim_walk);
}
} else if (self.velocity.y > 0) {
play_animation(self, anim_jump);
} else {
play_animation(self, anim_fall);
}
}After, those branches are states, and each state plays its animation once in enter:
idle: {
enter: () => sprite.play_flipbook("#sprite", anim_idle),
update: (ctx) =>
ctx.ground_contact && ctx.velocity.x !== 0 ? "/grounded/walk" : undefined,
},
walk: {
enter: () => sprite.play_flipbook("#sprite", anim_walk),
update: (ctx) =>
ctx.ground_contact && ctx.velocity.x === 0 ? "/grounded/idle" : undefined,
},m.state("/grounded/idle").enter(() => sprite.play_flipbook("#sprite", anim_idle));
m.state("/grounded/idle").update((ctx) =>
ctx.ground_contact && ctx.velocity.x !== 0 ? "/grounded/walk" : undefined,
);
m.state("/grounded/walk").enter(() => sprite.play_flipbook("#sprite", anim_walk));
m.state("/grounded/walk").update((ctx) =>
ctx.ground_contact && ctx.velocity.x === 0 ? "/grounded/idle" : undefined,
);- The state itself is the check.
JUMPis a rule of their parentgroundedalone, with arunthat sets the takeoff speed, so no flag guards the jump. - The script keeps the physics and hands the rest to the machine.
fixed_updatecallsself.motion.update(dt)while the contacts from the last physics step still hold, andon_inputsendsJUMPandJUMP_RELEASED. - A leaf's
updatehook checks what its parent checks.groundedleaves for/airbornewhenground_contactis lost, butupdatehooks run deepest first, soidleandwalkcheckground_contacttoo. Without it, a leaf whose velocity check fires on the step the ground disappears would move to its sibling, and the player would stay grounded for that step. - Give the machine an object, not
self.init's return value is copied onto the engine-ownedself, so a context built from loose fields ininitwould keep stale copies of them. The player'sinitbuilds onebodyobject, starts the machine on it and returns{ body, motion }; every hook then reads and writesself.body, the same object the machine sees. - A state is as fresh as its last update.
groundedreflects the contacts seen by the lastfixed_update, while the old check readground_contactafter the physics step that followed it. So the player can now jump on the one physics step after walking off a ledge, a single step of leniency the example accepts.
Cheat sheet
Short answers to common tasks. Each snippet is an excerpt of a guard machine: one with health that patrols, goes on alert, takes hits and dies, or a variant of it written for that row.
Configure a state
| I want to | Solution | Snippet |
|---|---|---|
|
Move to a state when an event arrives |
Name the target under |
|
|
Move only when a check passes |
A rule with |
|
|
Ask whether any of several states is active |
|
|
|
React to an event and stay in the state |
A rule with |
|
|
Move after a delay |
|
|
|
Run code at a set time without leaving the state |
A rule in |
|
|
Repeat an action while a state is active |
|
|
|
Decide where to go as soon as a state is entered |
|
|
|
Check something every frame |
|
|
|
Come back to the child that was active |
|
|
|
Wait for an engine callback |
|
|
|
Wait for several engine callbacks |
A |
|
|
Move on when every region has finished |
|
|
|
Run a second machine while a state is active |
Start it in the state's |
|
|
Clean up on every way out of a state |
|
|
|
Stop the machine from one of its states |
|
|
|
Restart a machine |
Stop the instance and start a new one from a script callback; see Restart a machine |
|
|
Resume a saved game in the state it was in |
Pass the saved |
|
|
Know whether an event would do anything |
|
|
|
Take a Defold message as an event |
List it in |
|
|
React to any event no state took |
|
|
|
Keep running instances through a hot reload |
Pass a key to the first call |
|
|
Start over when the script is hot reloaded |
Restart the machine in |
|
|
Keep fields only the machine uses |
|
|
Read types off the machine
Every type comes from the exported machine, so nothing is declared twice; see Types. import type is enough for these. The one type the machine does not give back is that of its private fields, which is declared once, beside the machine.
| I want to | Solution | Snippet |
|---|---|---|
|
Name the type of a running instance |
|
|
|
Name the context type |
Index the instance type |
|
|
Name the whole context a private machine's hooks see |
Intersect the context type with the private fields' type; |
|
|
Name every event the machine takes |
The parameter of |
|
|
Name every state path |
|
|
|
Name the event a message mapper builds |
What |
|
|
Pass an instance to a function |
Use the instance type as the parameter type |
|
|
Write a function for any machine with this context and these events |
Type the parameter |
|
Type self
| I want to | Solution | Snippet |
|---|---|---|
|
Get a typed |
Return the instance from |
|
|
Pass |
Name a |
|
|
Name |
Annotate what |
|
|
Start the machine after |
Make the field optional and check it before each use |
|
|
Set a timer's delay from a property |
Pass the property to |
|
Reference
StateConfig
Every field is optional on a state; the root config requires initial and states.
| Field | Type | Meaning |
|---|---|---|
type | "parallel" | Keep every child active at once, each as a region; see Run regions side by side with parallel. Not allowed on the root. |
initial | string | The full path of the child entered with this state (/on/bright inside on). Required when states is set, unless the state is parallel. |
restoreDepth | number | "all" | Enter the children that were active when this state was last left, this many levels down, instead of initial; see Resume with history. |
states | { [name: string]: StateConfig } | Child states, by name. A name is non-empty and contains no /. |
tags | readonly Tag[] | Names that hold while the state is active, read with hasTag; see Name a group of states with tags. |
on | { [type]: target | config | config[] } | Transitions by event type, each target a full path; see Events and transitions. |
after | { [seconds: number]: target | rule } | { delay, to, when, run }[] | Full-path targets taken after this long in the state, in game time, or rules with a to, a when and a run; see Rules on a timer. In the list form delay is a number or (ctx) => number, read once per entry of the state; see update and after. |
every | { [seconds: number]: run | run[] } | { delay, run }[] | Code run each time this many seconds pass on the state's clock while the state is active, without a move; see Repeat while a state is active. |
always | target | config | config[] | Full-path targets taken right after any move that leaves this state active; the first whose when(ctx, machine) is missing or passes wins, and its run(ctx, machine) runs during the move. See Move on at once with always. |
enter | (ctx, machine) => void | Runs each time the state is entered. |
exit | (ctx, machine) => void | Runs each time the state is left, including on stop(). |
update | (ctx, dt, machine) => target | undefined | Runs on every update(dt) while active; a returned target, one of the machine's full paths, transitions. |
task | (ctx, finish, machine) => (() => void) | void | Runs after enter; finish(event) sends one event if the state is still the one entered. A returned function runs once when that entry ends. |
unhandled | (ctx, event, machine) => void | Runs when the machine drops an event while the state is active; see React to an unhandled event. |
invoke | never | Renamed to task; setting it fails to compile. |
PrivateCtxConfig
The optional key the root config takes; see Private fields with privateCtx.
| Field | Type | Meaning |
|---|---|---|
privateCtx | (ctx: Ctx) => Priv | Builds the fields only the machine uses from the object passed to start. Runs once per start, before the root's enter hook, so every instance gets fresh fields of its own. |
Machine
What the second defineMachine call returns.
| Member | Type | Meaning |
|---|---|---|
start | (ctx: Ctx, at?: readonly P[]) => MachineInstance<Ctx, E, P, Tag> | Creates an instance and enters initial, or the states the paths of at name; see Start at saved paths. |
MachineInstance
| Member | Type | Meaning |
|---|---|---|
ctx | Ctx | The context passed to start. A private machine's fields are on the same table and absent from its type. |
path | P | undefined | The deepest active state's full path (the first region's leaf in a parallel state), or undefined once stopped. |
leaves | readonly P[] | Every active leaf's full path, in region order; one path without parallel states, empty once stopped. The same array, updated in place. |
matches | (path: P) => boolean | Whether the state at the full path path is active, ancestors included. |
hasTag | (tag: Tag) => boolean | Whether an active state carries tag, parents and every region included. |
can | (event: E) => boolean | Whether a rule of an active state would take event if it were sent at that moment. Moves nothing and runs no hook. |
send | (event: E) => void | Handles event, or queues it when called during a step. |
update | (dt: number) => void | Runs the update hooks, then, in every region no hook moved, each state's every entries and its after timers. |
stop | () => void | Exits every active state; later send and update calls do nothing. |
onMove | (listener: (from, to, cause, event) => void) => () => void | Calls listener after each move with the old and new leaf, the cause and the event; inside a parallel state, the leaves are those of the region that moved. to is undefined on stop(). Returns a function that removes the listener. |
onUnhandled | (listener: (event: E) => void) => () => void | Calls listener with each event the machine processes that no rule of an active state takes. Returns a function that removes the listener. |
WaitGroup
waitGroup() returns a group that counts the engine work a task started and tells when all of it has finished.
import { defineMachine, waitGroup } from "@defold-typescript/types/hsm";
interface LevelCtx {
readonly url: string;
readonly curtain: Url;
}
type LevelEvent = { type: "READY" };
export const level = defineMachine<LevelCtx, LevelEvent>()({
initial: "/loading",
states: {
loading: {
task: (ctx, finish) => {
const group = waitGroup();
http.request(ctx.url, "GET", group.add());
go.animate(ctx.curtain, "tint.w", go.PLAYBACK_ONCE_FORWARD, 0, go.EASING_LINEAR, 0.5, 0, group.add());
group.wait(() => finish({ type: "READY" }));
},
on: { READY: "/playing" },
},
playing: {},
},
});| Member | Type | Meaning |
|---|---|---|
add | () => () => void | Records one pending piece of work and returns the function that reports it finished. That function counts once and ignores its arguments. |
wait | (callback: () => void) => void | Calls callback once when nothing added is pending: at once when nothing is pending at the call, and otherwise inside the report that finishes the last piece. |
A group knows nothing about a machine. Built inside a task, it is new for each entry of the state. A report that arrives after the state was left ends in a finish that is ignored, and a piece that never reports is a case for the watchdog. Work that completes has a group with a piece that can fail and one counted while the game runs, and A group inside a sequence waits on one with await.
MachineBuilder
What the second buildMachine call returns; see Write a machine as statements. P is the union of the skeleton's paths.
| Member | Type | Meaning |
|---|---|---|
state | (path: P) => StateBuilder | The builder of the state at the full path path. A path the skeleton lacks throws. |
root | StateBuilder | The root's builder, whose rules take an event no state below it takes. |
build | () => Machine<Ctx, E, P, Tag> | Writes the statements onto the skeleton's state objects and defines the machine with defineMachine and the key. Throws, naming the state, on a rule left without its ending, and on a second call. |
StateBuilder
Each on, after, every and always call adds one entry, in call order. A state's on, every and always entries are tried in that order, and its after timers in delay order, call order breaking ties. Every call throws after build().
| Member | Type | Meaning |
|---|---|---|
on | (type) => { when, to, run, ignore } | Adds a rule for the event type, whose when and run see that variant: when(guard) first if any, then to(path) (optionally followed by run), run(...actions) or ignore(). |
after | (delay: number | (ctx) => number) => { when, to, run } | Adds a timer: when(guard) first if any, then to(path) (optionally followed by run) or run(...actions); see Rules on a timer. |
every | (delay: number | (ctx) => number) => { run } | Adds run(...actions), run each time the delay passes; see Repeat while a state is active. |
always | () => { when, to } | Adds a rule taken right after a move that leaves the state active: when(guard) first if any, then to(path), optionally followed by run. |
enter | (hook: (ctx, machine) => void) => void | Sets the function run each time the state is entered. A second call throws. |
exit | (hook: (ctx, machine) => void) => void | Sets the function run each time the state is left. A second call throws. |
update | (hook: (ctx, dt, machine) => P | undefined) => void | Sets the function run on every update(dt) while the state is active; a returned path moves there. A second call throws. |
task | (start: (ctx, finish, machine) => (() => void) | void) => void | Sets the work started on each entry; see Engine callbacks. A second call throws. |
unhandled | (hook: (ctx, event, machine) => void) => void | Sets the function run when the machine drops an event while the state is active. A second call throws. |
tags | (...names: Tag[]) => void | Adds names that hold while the state is active, read with hasTag. |