Skip to content

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:

luau
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 ​

luau
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 }?,
}
FieldTypeDefaultDescription
states{ [Name]: State }?nilThe child states. A state with children is a superstate.
initialName?nilThe child entered with the state. Required when it has states.
durationDuration?nilHow long until onTimeUp. See Timed states.
on{ [Event]: Handler }?nilThe handler for each event this state handles.
onTimeUpHandler?nilHandles the end of duration, in this state or a child.
onStart(context, run) -> ()nilRuns when the state is entered.
onProcess(context, run, now) -> (GoTo | Stay)?nilRuns on each process. Return a goTo to move. stay and nil both let the next onProcess run.
onEnd(context, run) -> ()nilRuns when the state is left.
record(context, run) -> RecordnilAdds each entry to the machine's history.
rememberboolean?falseEnters the child it was last in, rather than initial. See Remembering a child.
cooldownnumber?nilSeconds after leaving before it can be entered again. See Cooldowns.
canEnter(context, data) -> booleannilWhether the state may be entered. See Entry conditions.
timeline{ [number]: (context, run) -> () }?nilFunctions run at set seconds into the state. See Timelines.
tags{ string }?nilNames 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 to process.

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.

luau
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)?. Return S.goTo(name, data) to move, S.stay() to take the event without moving, or nil to 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.

luau
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.

luau
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.

luau
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 process runs every function whose time has come since the last one, in order of time, so a slow frame does not skip any. A function at 0 runs on the first process after the state is entered.
  • A function at the same time as the end of duration runs before onTimeUp. One after it runs only if the time-up does not move the machine.
  • The times follow pausing and the time scale, as duration does, and are kept in a snapshot.
  • A timeline's functions are for side effects. To move, send an event or call goTo from one: the move happens once the functions due have run.
CauseMessage
ErrorA key of timeline is not a number of 0 or more, or a value is not a functionCanopy.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.

luau
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;
  • goTo returns false;
  • a goTo returned from onProcess is ignored, and the next onProcess runs.

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.

luau
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.

luau
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,
})
CauseMessage
ErrorcanEnter is not a functionCanopy.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.

luau
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({}),
			},
		}),
	},
})
luau
humanoid.WalkSpeed = if machine:hasTag("canMove") then 16 else 0

The 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.

CauseMessage
Errortags holds something that is not a stringCanopy.state: 'tags' must be a list of tag names.
Errortags holds a tag not in the setup's tagsCanopy.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:

  1. its onEnd,
  2. the machine's onExit hook.

Then each state it enters runs, outermost first:

  1. its memory factory,
  2. its record, when the machine has a history,
  3. its onStart,
  4. the machine's onEnter hook.

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.