Skip to content

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:

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

  1. finds the part of the current path that the target's path shares,
  2. leaves every state below it, innermost first,
  3. enters every state down to the target, then the target's initial child and its initial child, 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 ​

luau
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
): boolean

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

CauseMessage
Erroroptions.buffer is not a number of 0 or moreCanopy: '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:

  • after each move made by send or goTo, and
  • on each process, including in a group,

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.

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

luau
machine:isBuffered(event: Event): boolean

Returns whether event is kept, waiting to be tried again.

clearBuffer Added in 0.1.0 ​

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

luau
machine:process(now: number): boolean

Advances the machine to now:

  1. Each state whose run.endsAt has passed runs its time-up, from that state outwards, once per stay.
  2. Each state's onProcess runs, outermost first. The first one to return a goTo moves the machine.
  3. After a move, it starts again from step 1, until nothing moves or it has made maxMoves moves.

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 as options.at, such as os.clock().
CauseMessage
WarningmaxMoves moves were made in one callCanopy: stopped after <moves> moves in one process, at '<path>'.
WarningonProcess returned something that is not a goTo or stayCanopy: '<name>' returned something that is not a goTo or stay from onProcess.
WarningA handler function returned something that is not a goTo or stayCanopy: a handler of '<name>' returned something that is not a goTo or stay.

goTo Added in 0.1.0 ​

luau
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
): boolean

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

CauseMessage
WarningThe 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 ​

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

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

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

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

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

luau
machine:isPaused(): boolean

Returns whether pause was called without a resume since.

setTimeScale Added in 0.1.0 ​

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

CauseMessage
Errorscale is not more than 0, or is math.hugeCanopy: the time scale must be more than 0.

getTimeScale Added in 0.1.0 ​

luau
machine:getTimeScale(): number

Returns the time scale, 1 unless changed.

Reading the machine ​

isIn Added in 0.1.0 ​

luau
machine:isIn(name: Name): boolean

Returns whether the machine is in name, or in a state inside it.

hasTag Added in 0.1.0 ​

luau
machine:hasTag(tag: string): boolean

Returns whether a state on the active path has tag in its tags. A stopped machine has no tags.

CauseMessage
Warningtag 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 ​

luau
machine:getTags(): { string }

Returns the tags of every state on the active path, sorted, in a new list.

canSend Added in 0.1.0 ​

luau
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
): boolean

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

luau
machine:getPath(): { Name }

Returns a copy of the names of the states the machine is in, outermost first.

getLeaf Added in 0.1.0 ​

luau
machine:getLeaf(): Name?

Returns the innermost state the machine is in, or nil once it has stopped.

getRun Added in 0.1.0 ​

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

luau
machine:isCoolingDown(name: Name, at: number?): boolean

Returns whether name was left less than its cooldown ago, at at or the last process time.

getCooldownEnd Added in 0.1.0 ​

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

luau
machine:isStopped(): boolean

Returns whether stop has been called.

getContext Added in 0.1.0 ​

luau
machine:getContext(): Context

Returns the context the machine was made with.

getTree Added in 0.1.0 ​

luau
machine:getTree(): Tree<Context, Event, Name, Data, Record>

Returns the tree the machine was made from.

getHistory Added in 0.1.0 ​

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

luau
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)
end

getTrace Added in 0.1.0 ​

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

luau
type TraceEntry<Event, Name, Data> = {
	event: Event?,
	isTimeUp: boolean,
	data: Data?,
	at: number,
	handledBy: Name?,
	hasMoved: boolean,
}
FieldDescription
eventThe event sent, nil for a time-up.
isTimeUpWhether this was the end of a duration rather than an event.
dataThe event's data.
atThe time of the event, or the end of the duration for a time-up.
handledByThe state whose handler took it, nil when no state did.
hasMovedWhether 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.

luau
machine:send("spotted", nil, os.clock())
remote:FireAllClients(enemyId, machine:getSnapshot())
luau
remote.OnClientEvent:Connect(function(enemyId, snapshot)
	machines[enemyId] = S.restore(EnemyStates.tree, contextOf(enemyId), snapshot)
end)

getSnapshot Added in 0.1.0 ​

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

luau
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?,
}
FieldDescription
runsThe 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.
timeThe last process time.
pausedAtWhen the machine was paused, nil while running.
timeScaleThe time scale, nil for 1.
cooldownEndsWhen each state left with a cooldown can be entered again.
rememberedThe child each remember state was last in.

Options ​

MachineOptions Added in 0.1.0 ​

luau
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?,
}
FieldTypeDefaultDescription
atnumber?0The start time. Pass the clock you will pass to process.
hooksHooks?{}Functions told about each move.
randomRandom?math.randomRolls { min, max } durations. Pass a seeded Random for repeatable runs.
maxMovesnumber?16How many moves one process may make, so states that send each other back and forth cannot hang.
historyHistory?nilWhere the entries of recorded states go. Without one, nothing is recorded.
timeScalenumber?1How fast durations run. See Pausing and slowing.
tracenumber?nilHow many events and time-ups to keep for getTrace. None by default.

Hooks Added in 0.1.0 ​

luau
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's onStart, with the state's name and run.
  • onExit — after a state's onEnd, 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.