States
A state is built with S.state, or with S.withMemory when it keeps data of its own. Every field is optional.
The examples on this page use this setup:
const Canopy = require("@Canopy")
type Context = { model: Model, target: Model? }
type Event = "spotted" | "lost" | "hit"
type Name = "idle" | "fighting" | "chasing" | "attacking" | "stunned"
const S = Canopy.setup<<Context, Event, Name, Model, nil>>()State definition Added in 0.1.0
type StateDefinition<Context, Event, Name, Data, Memory, Record> = {
states: { [Name]: State<Context, Event, Name, Data, Record> }?,
initial: Name?,
duration: Duration?,
on: { [Event]: Handler<Context, Name, Data, Memory> }?,
onTimeUp: Handler<Context, Name, Data, Memory>?,
onStart: ((context: Context, run: Run<Name, Data, Memory>) -> ())?,
onProcess: ((context: Context, run: Run<Name, Data, Memory>, now: number) -> (GoTo<Name, Data> | Stay)?)?,
onEnd: ((context: Context, run: Run<Name, Data, Memory>) -> ())?,
record: ((context: Context, run: Run<Name, Data, Memory>) -> Record)?,
remember: boolean?,
cooldown: number?,
canEnter: ((context: Context, data: Data?) -> boolean)?,
timeline: { [number]: (context: Context, run: Run<Name, Data, Memory>) -> () }?,
tags: { string }?,
}| Field | Type | Default | Description |
|---|---|---|---|
states | { [Name]: State }? | nil | The child states. A state with children is a superstate. |
initial | Name? | nil | The child entered with the state. Required when it has states. |
duration | Duration? | nil | How long until onTimeUp. See Timed states. |
on | { [Event]: Handler }? | nil | The handler for each event this state handles. |
onTimeUp | Handler? | nil | Handles the end of duration, in this state or a child. |
onStart | (context, run) -> () | nil | Runs when the state is entered. |
onProcess | (context, run, now) -> (GoTo | Stay)? | nil | Runs on each process. Return a goTo to move. stay and nil both let the next onProcess run. |
onEnd | (context, run) -> () | nil | Runs when the state is left. |
record | (context, run) -> Record | nil | Adds each entry to the machine's history. |
remember | boolean? | false | Enters the child it was last in, rather than initial. See Remembering a child. |
cooldown | number? | nil | Seconds after leaving before it can be entered again. See Cooldowns. |
canEnter | (context, data) -> boolean | nil | Whether the state may be entered. See Entry conditions. |
timeline | { [number]: (context, run) -> () }? | nil | Functions run at set seconds into the state. See Timelines. |
tags | { string }? | nil | Names the state, and every state inside it, has. See Tags. |
The functions get:
context: Context— the machine's context.run: Run<Name, Data, Memory>— this stay in the state. See Run.now: number— the time passed toprocess.
Nested states
A state with states holds other states, and its initial names the child entered with it. While a child is active, its superstate is active too, so machine:isIn("fighting") is true while the machine is in attacking.
Names are used once in the whole tree, not once per parent, so machine:goTo("attacking") always means one state.
const fighting = S.state({
initial = "chasing",
on = {
lost = "idle",
hit = "stunned",
},
states = {
chasing = S.state({}),
attacking = S.state({}),
},
})lost and hit are handled by fighting, so they work the same in chasing and attacking.
Handlers
A handler decides what an event does. It is one of:
- A state's name. The machine moves to that state.
- A function
(context: Context, run: Run<Name, Data, Memory>, data: Data?) -> (GoTo<Name, Data> | Stay)?. ReturnS.goTo(name, data)to move,S.stay()to take the event without moving, ornilto pass the event on to the outer states.
An event goes to the innermost active state first, then to each superstate outwards. The first state whose handler takes it decides, and the states outside it never see the event. An event that no state takes does nothing.
const chasing = S.state({
on = {
-- Only a hit from the target interrupts the chase; any other hit goes up to `fighting`.
hit = function(context, run, attacker)
return if attacker == context.target then S.goTo("attacking") else nil
end,
-- A taunt is ignored while chasing, so `fighting` never sees it.
taunted = function(context, run)
context.angerLevel += 1
return S.stay()
end,
},
})Timed states
A state with a duration runs onTimeUp once it has lasted that long. duration is seconds, or { min, max }, rolled again on each entry. The end time is run.endsAt, which onStart may change.
onTimeUp is a handler, and it passes outwards like an event: when a timed child has no onTimeUp, its superstate's handler takes it. The time-up happens at run.endsAt, not at the later time process noticed it, so the state entered starts at the exact end.
const stunned = S.state({
duration = {
1,
2,
},
onTimeUp = "fighting",
})Timelines
A state's timeline runs functions at set seconds after the state is entered, such as the frames of an attack: a sound at the start, a hitbox at 0.2 seconds, a trail at 0.35. Each function runs once per entry, from process, and only while the machine is still in the state.
const slash = S.state({
duration = 0.6,
onTimeUp = "free",
timeline = {
[0] = function(context)
context.sounds.Slash:Play()
end,
[0.2] = function(context, run)
context.spawnHitbox(run.data)
end,
[0.35] = function(context)
context.trail.Enabled = false
end,
},
})- A
processruns every function whose time has come since the last one, in order of time, so a slow frame does not skip any. A function at0runs on the firstprocessafter the state is entered. - A function at the same time as the end of
durationruns beforeonTimeUp. One after it runs only if the time-up does not move the machine. - The times follow pausing and the time scale, as
durationdoes, and are kept in a snapshot. - A timeline's functions are for side effects. To move, send an event or call
goTofrom one: the move happens once the functions due have run.
| Cause | Message | |
|---|---|---|
| Error | A key of timeline is not a number of 0 or more, or a value is not a function | Canopy.state: 'timeline' maps seconds (0 or more) to functions. |
Remembering a child
A superstate with remember = true enters the child it was last in, rather than its initial child. Use it for something that an interruption should resume, such as a three-step attack cut off by a stun. The remembered child is used whenever the superstate is entered without a deeper target, including when it is entered again while the machine is in it. A move that names a child goes to that child.
Each machine remembers on its own. forget clears what a state remembers, so it enters initial again.
const attacking = S.state({
initial = "first",
remember = true,
on = {
stunned = "stunned",
},
states = {
first = S.state({
on = {
next = "second",
},
}),
second = S.state({}),
},
})Cooldowns
A state with a cooldown cannot be entered again until that many seconds after it was left. A move that would enter it, at any depth, is refused and changes nothing:
- an event or time-up handler that leads to it passes the event on to the outer states, as if the state had no handler, so an outer state can offer a fallback;
goToreturnsfalse;- a
goToreturned fromonProcessis ignored, and the nextonProcessruns.
Entering the state the machine is already in counts as entering it, so a skill with a cooldown cannot be restarted by sending its event again. The cooldown is measured with the time of the move, and runs in real time: pausing or slowing the machine does not stretch it. Read it with isCoolingDown, and end it early with resetCooldown.
const dashing = S.state({
cooldown = 2,
duration = 0.5,
onTimeUp = "walking",
})Entry conditions
A state's canEnter decides whether it may be entered, from the context and the data the move carries. A move it refuses is refused as a cooldown refuses one: nothing changes, an event passes on to the outer states, and goTo returns false. Use it for a cost or a requirement that lives in the context, such as stamina for an attack or a target in range.
It runs for every state the move would enter, including the children entered by initial and the state the machine is already in when the move enters it again. It also runs from canSend, so it should only read, not change anything.
const free = S.state({
on = {
-- Without stamina the attack is refused, and `free` stays.
attack = "attacking",
},
})
const attacking = S.state({
canEnter = function(context)
return context.stamina >= 10
end,
onStart = function(context)
context.stamina -= 10
end,
})| Cause | Message | |
|---|---|---|
| Error | canEnter is not a function | Canopy.state: 'canEnter' must be a function. |
Tags
A state's tags name what the machine may do, or what it is, while in that state or any state inside it. Ask with hasTag rather than listing states: the code that reads a tag does not change when a state is added or renamed.
const tree = S.tree({
initial = "free",
states = {
free = S.state({
tags = { "canMove", "canAttack" },
}),
stunned = S.state({
initial = "dazed",
tags = { "isHurt" },
states = {
-- Has `isHurt` from `stunned`, and `canMove` of its own.
dazed = S.state({
tags = { "canMove" },
}),
frozen = S.state({}),
},
}),
},
})humanoid.WalkSpeed = if machine:hasTag("canMove") then 16 else 0The type checker does not check tags. Give setup the list of every tag to have each state's tags checked when it is built, and hasTag warn about a tag outside the list.
| Cause | Message | |
|---|---|---|
| Error | tags holds something that is not a string | Canopy.state: 'tags' must be a list of tag names. |
| Error | tags holds a tag not in the setup's tags | Canopy.state: '<tag>' is not one of the tags given to setup. |
Memory
A state built with withMemory has run.memory, made by its factory on each entry, before onStart, and dropped when the state is left. Without a factory, run.memory is nil.
Memory is the state's own. A child cannot read its superstate's memory through its own run. Data that several states share, or that must outlive a stay, belongs in the context.
Order of a move
When the machine moves, each state it leaves runs, innermost first:
- its
onEnd, - the machine's
onExithook.
Then each state it enters runs, outermost first:
- its memory factory,
- its
record, when the machine has a history, - its
onStart, - the machine's
onEnterhook.
After the move, the machine's onChanged hook runs once. A goTo or send called from any of these functions waits until the move has finished.