Machines
A machine is made from a tree with S.new. It keeps the states it is in and one run for each, and it reads no clock: every call that moves it uses the time you pass, or the time of the last process.
The examples on this page use a machine like this:
const ReplicatedStorage = game:GetService("ReplicatedStorage")
const EnemyStates = require(ReplicatedStorage.EnemyStates)
const S = EnemyStates.S
const machine = S.new(EnemyStates.tree, {
model = workspace.Goblin,
target = nil,
}, {
at = os.clock(),
})How a machine moves
A machine is always in a path of states, from an outermost state down to an innermost one. A move to a target:
- finds the part of the current path that the target's path shares,
- leaves every state below it, innermost first,
- enters every state down to the target, then the target's
initialchild and itsinitialchild, until a state with no children.
A target that is already in the path is left and entered again, with a new run. A target the tree does not have leaves the machine where it is, with one warning per tree and name.
Moving the machine
send Added in 0.1.0
machine:send(
event: Event, -- The event's name
data: Data?, -- Passed to a handler function, and to the states entered
at: number?, -- The time of the event; the last process time by default
options: SendOptions? -- { buffer: number? }, to keep an event no state takes
): booleanSends an event to the innermost state, then outwards until a state's handler takes it. Returns whether the machine moved. Called while the machine is moving, the event waits until the move has finished, and send returns false.
With options.buffer, an event no state takes is kept for that many seconds and tried again. See Buffering input.
| Cause | Message | |
|---|---|---|
| Error | options.buffer is not a number of 0 or more | Canopy: 'buffer' must be seconds, 0 or more. |
Buffering input
A player who presses attack a moment before the current attack ends expects the next one to come out. Send the input with a buffer, and an event no state takes, or one whose move a cooldown or canEnter refuses, is kept and tried again:
until a state takes it, or buffer seconds after it was sent. The time is real time: pausing or slowing the machine does not stretch it.
UserInputService.InputBegan:Connect(function(input, isProcessed)
if not isProcessed and input.UserInputType == Enum.UserInputType.MouseButton1 then
machine:send("attack", nil, os.clock(), {
buffer = 0.25,
})
end
end)One copy of each event is kept: sending it again with a buffer replaces the kept one, with the new data and expiry. A retry is traced only when a state takes it. The buffer is left out of snapshots, and stop clears it.
isBuffered Added in 0.1.0
machine:isBuffered(event: Event): booleanReturns whether event is kept, waiting to be tried again.
clearBuffer Added in 0.1.0
machine:clearBuffer(event: Event?): ()Drops event from the buffer, or every kept event when event is nil. Use it when an input should no longer count, such as when the player lets go of a held button.
process Added in 0.1.0
machine:process(now: number): booleanAdvances the machine to now:
- Each state whose
run.endsAthas passed runs its time-up, from that state outwards, once per stay. - Each state's
onProcessruns, outermost first. The first one to return agoTomoves the machine. - After a move, it starts again from step 1, until nothing moves or it has made
maxMovesmoves.
Returns whether the machine moved. A machine that is moving or stopped returns false at once.
now: number— the current time, in the same clock asoptions.at, such asos.clock().
| Cause | Message | |
|---|---|---|
| Warning | maxMoves moves were made in one call | Canopy: stopped after <moves> moves in one process, at '<path>'. |
| Warning | onProcess returned something that is not a goTo or stay | Canopy: '<name>' returned something that is not a goTo or stay from onProcess. |
| Warning | A handler function returned something that is not a goTo or stay | Canopy: a handler of '<name>' returned something that is not a goTo or stay. |
goTo Added in 0.1.0
machine:goTo(
target: Name, -- The state to move to
data: Data?, -- Reaches every state entered, as run.data
at: number? -- The time of the move; the last process time by default
): booleanMoves the machine to target at once, as a returned goTo would. Returns false when the tree has no state named target, or when a state it would enter is cooling down or refuses the move. Called while the machine is moving, the move waits until the current one has finished, and goTo returns whether the tree has target.
| Cause | Message | |
|---|---|---|
| Warning | The tree has no state named target (once per tree and name) | Canopy: '<target>' is not in the tree, so the machine stays where it is. |
resetCooldown Added in 0.1.0
machine:resetCooldown(name: Name?): ()Ends the cooldown of name, or of every state when name is nil, so it can be entered at once.
forget Added in 0.1.0
machine:forget(name: Name?): ()Clears the child that name remembers, or what every state remembers when name is nil, so the state enters its initial child again.
stop Added in 0.1.0
machine:stop(): ()Leaves every state, innermost first, running onEnd and onExit for each, and stops the machine for good. A stopped machine ignores send, goTo and process. Call it when the owner is removed.
Pausing and slowing
Hitstop, stuns and slow motion change how fast a machine's timed states run, without changing the clock passed to process. run.startedAt and run.endsAt stay in that clock: pausing or scaling moves run.endsAt so that the time each state has left is kept, or stretched.
Only durations are affected. Cooldowns and the times recorded in the history run in real time.
pause Added in 0.1.0
machine:pause(at: number?): ()Freezes every duration at at, the last process time by default. While paused, process does nothing: no time-ups and no onProcess. Events and goTo still move the machine, and a state entered while paused starts its duration when the machine resumes. Pausing a paused machine does nothing.
resume Added in 0.1.0
machine:resume(at: number?): ()Unfreezes the durations at at, pushing the end of each back by the time it spent paused. An end that had already passed before the pause stays where it is, so the next process runs its time-up.
isPaused Added in 0.1.0
machine:isPaused(): booleanReturns whether pause was called without a resume since.
setTimeScale Added in 0.1.0
machine:setTimeScale(scale: number, at: number?): ()Changes how fast durations run from at on. 2 makes them run twice as fast and 0.5 half as fast. The time each timed state has left is stretched or shrunk to match, and every duration rolled after is divided by scale. Set it on a paused machine to change the time left that resume will start from.
| Cause | Message | |
|---|---|---|
| Error | scale is not more than 0, or is math.huge | Canopy: the time scale must be more than 0. |
getTimeScale Added in 0.1.0
machine:getTimeScale(): numberReturns the time scale, 1 unless changed.
Reading the machine
isIn Added in 0.1.0
machine:isIn(name: Name): booleanReturns whether the machine is in name, or in a state inside it.
hasTag Added in 0.1.0
machine:hasTag(tag: string): booleanReturns whether a state on the active path has tag in its tags. A stopped machine has no tags.
| Cause | Message | |
|---|---|---|
| Warning | tag is not in the setup's tags (once per tree and tag) | Canopy: '<tag>' is not one of the tags given to setup. |
getTags Added in 0.1.0
machine:getTags(): { string }Returns the tags of every state on the active path, sorted, in a new list.
canSend Added in 0.1.0
machine:canSend(
event: Event,
data: Data?, -- What the event would carry, passed to each canEnter
at: number? -- The time to check cooldowns at; the last process time by default
): booleanReturns whether a state the machine is in has a handler for event, without sending it. Use it to grey out a button, or to keep an input buffered until the machine can take it. A handler function counts, even though it may return nil and pass the event on, because finding out would mean calling it. A handler naming a state that a move would not enter, because it is cooling down at at or its canEnter refuses data, does not count. A stopped machine returns false.
canSend runs each canEnter on the way, so keep them free of side effects.
getPath Added in 0.1.0
machine:getPath(): { Name }Returns a copy of the names of the states the machine is in, outermost first.
getLeaf Added in 0.1.0
machine:getLeaf(): Name?Returns the innermost state the machine is in, or nil once it has stopped.
getRun Added in 0.1.0
machine:getRun(name: Name): RunInfo<Name, Data>?Returns the run of name while the machine is in it, or nil. A state's memory is its own, so it is not included.
isCoolingDown Added in 0.1.0
machine:isCoolingDown(name: Name, at: number?): booleanReturns whether name was left less than its cooldown ago, at at or the last process time.
getCooldownEnd Added in 0.1.0
machine:getCooldownEnd(name: Name): number?Returns when name could be entered again after it was last left, even when that time has passed. Returns nil for a state with no cooldown, one never left, one the machine is in, or one whose cooldown was reset.
isStopped Added in 0.1.0
machine:isStopped(): booleanReturns whether stop has been called.
getContext Added in 0.1.0
machine:getContext(): ContextReturns the context the machine was made with.
getTree Added in 0.1.0
machine:getTree(): Tree<Context, Event, Name, Data, Record>Returns the tree the machine was made from.
getHistory Added in 0.1.0
machine:getHistory(): History<Name, Record>?Returns the history given in its options, or nil.
Tracing
When a machine does not do what you expect, the trace says why: each event and time-up, the state whose handler took it, and whether the machine moved. An event no state handles shows up with handledBy = nil. Keep the last entries with options.trace, or get each one as it happens with the onEvent hook. A machine with neither does no work for it.
const machine = S.new(CharacterStates.tree, context, {
trace = 32,
})
-- Later, when something looks wrong:
for _, entry in machine:getTrace(10) do
print(entry.at, entry.event or "time up", entry.handledBy or "ignored", entry.hasMoved)
endgetTrace Added in 0.1.0
machine:getTrace(count: number?): { TraceEntry<Event, Name, Data> }Returns copies of the last count entries, or all of those kept, oldest first. Empty unless options.trace was given.
TraceEntry Added in 0.1.0
type TraceEntry<Event, Name, Data> = {
event: Event?,
isTimeUp: boolean,
data: Data?,
at: number,
handledBy: Name?,
hasMoved: boolean,
}| Field | Description |
|---|---|
event | The event sent, nil for a time-up. |
isTimeUp | Whether this was the end of a duration rather than an event. |
data | The event's data. |
at | The time of the event, or the end of the duration for a time-up. |
handledBy | The state whose handler took it, nil when no state did. |
hasMoved | Whether the machine moved. |
Snapshots
A snapshot is where a machine stands, as plain data: tables, strings, numbers and booleans. Send it through a RemoteEvent so a client can show the server's state, or save it and restore it later. It holds every run's name, data and times, and the machine's time, pause, time scale, cooldowns and remembered children. It does not hold the states' memory, which restore makes again, or the history, which you keep yourself.
data is copied by reference, so keep it to values a RemoteEvent can carry when the snapshot is sent.
machine:send("spotted", nil, os.clock())
remote:FireAllClients(enemyId, machine:getSnapshot())remote.OnClientEvent:Connect(function(enemyId, snapshot)
machines[enemyId] = S.restore(EnemyStates.tree, contextOf(enemyId), snapshot)
end)getSnapshot Added in 0.1.0
machine:getSnapshot(): Snapshot<Name, Data>Returns where the machine stands. Each call makes new tables, so changing a snapshot does not change the machine.
Snapshot Added in 0.1.0
type Snapshot<Name, Data> = {
runs: { SnapshotRun<Name, Data> },
time: number,
pausedAt: number?,
timeScale: number?,
cooldownEnds: { [Name]: number }?,
remembered: { [Name]: Name }?,
}
type SnapshotRun<Name, Data> = {
name: Name,
data: Data?,
startedAt: number,
endsAt: number?,
isTimeUp: boolean,
cue: number?,
cueAt: number?,
}| Field | Description |
|---|---|
runs | The runs of the states the machine is in, outermost first. A run's endsAt is nil for a state with no duration, because math.huge cannot be saved as JSON. A run's cue and cueAt are the next cue of its timeline and when it runs, nil once every cue has run. |
time | The last process time. |
pausedAt | When the machine was paused, nil while running. |
timeScale | The time scale, nil for 1. |
cooldownEnds | When each state left with a cooldown can be entered again. |
remembered | The child each remember state was last in. |
Options
MachineOptions Added in 0.1.0
type MachineOptions<Context, Event, Name, Data, Record = nil> = {
at: number?,
hooks: Hooks<Context, Event, Name, Data>?,
random: Random?,
maxMoves: number?,
history: History<Name, Record>?,
timeScale: number?,
trace: number?,
}| Field | Type | Default | Description |
|---|---|---|---|
at | number? | 0 | The start time. Pass the clock you will pass to process. |
hooks | Hooks? | {} | Functions told about each move. |
random | Random? | math.random | Rolls { min, max } durations. Pass a seeded Random for repeatable runs. |
maxMoves | number? | 16 | How many moves one process may make, so states that send each other back and forth cannot hang. |
history | History? | nil | Where the entries of recorded states go. Without one, nothing is recorded. |
timeScale | number? | 1 | How fast durations run. See Pausing and slowing. |
trace | number? | nil | How many events and time-ups to keep for getTrace. None by default. |
Hooks Added in 0.1.0
type Hooks<Context, Event, Name, Data> = {
onEnter: ((context: Context, name: Name, run: RunInfo<Name, Data>) -> ())?,
onExit: ((context: Context, name: Name, run: RunInfo<Name, Data>) -> ())?,
onChanged: ((context: Context, path: { Name }, previousPath: { Name }, at: number) -> ())?,
onEvent: ((context: Context, entry: TraceEntry<Event, Name, Data>) -> ())?,
}Hooks tell the owner what the machine does, without adding code to every state. Use them to play animations, replicate the state, or log.
onEnter— after a state'sonStart, with the state's name and run.onExit— after a state'sonEnd, with the state's name and run.onChanged— once after each move, with copies of the new and the previous path, and the time of the move.onEvent— after each event and time-up, with a copy of its trace entry: which state handled it, if any, and whether the machine moved.