Skip to content

StateMachine

StateMachine is a finite state machine of named states and events: a wizard’s steps, a drawing tool’s modes, a connection’s life. Transitions are declared once (“in this state, this event leads to that state”) and the machine is driven by events. From 0.72.

#import "StateMachine.xc" // not in the Foundation umbrella: import it by name
StateMachine* m = StateMachine.withInitial(String.withCString("idle"));
m.addTransition(String.withCString("idle"), String.withCString("start"), String.withCString("running"));
m.addTransition(String.withCString("running"), String.withCString("stop"), String.withCString("idle"));
m.fire(String.withCString("start")); // true: now "running"
m.fire(String.withCString("start")); // false: "running" has no "start"
m.back(); // true: "idle" again

States and events are Strings compared by value. Declaring the same state and event again replaces the target. fire moves only when the current state has a transition for the event; back returns to the state before the last move, for a wizard’s Back button.

Creating · withInitial · addTransition · setDidChange

The state · state · isIn · setState

Driving · fire · canFire · targetOf · events · back · depth


static StateMachine* withInitial(String* state)

A machine in state, with no transitions yet.

void addTransition(String* from, String* event, String* to)

In from, event leads to to.

void setDidChange(callback method void(String* from, String* event, String* to))

Calls method (a bound method, &watcher.moved) after each fire that moves, with the state left, the event and the state entered. Null stops the calls. back and setState do not call it.

↑ Topics

String* state(void)
bool isIn(String* state)
void setState(String* state)

Puts the machine in state without a transition and forgets the history: a start or a reset.

↑ Topics

bool fire(String* event)

Moves if the current state has a transition for event, and reports whether it did.

bool canFire(String* event)
String* targetOf(String* event)

Where event leads from the current state, or null.

Array* events(void)

The events the current state has transitions for, in the order they were declared: what a UI enables.

bool back(void)

Returns to the state before the last move; false when there is none.

u32 depth(void) // u16 on the 6502

How many moves back can undo.

↑ Topics