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 nameOverview
Section titled “Overview”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" againStates 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.
Topics
Section titled “Topics”Creating · withInitial · addTransition · setDidChange
The state · state · isIn · setState
Driving · fire · canFire · targetOf · events · back · depth
Creating
Section titled “Creating”withInitial
Section titled “withInitial”static StateMachine* withInitial(String* state)A machine in state, with no transitions yet.
addTransition
Section titled “addTransition”void addTransition(String* from, String* event, String* to)In from, event leads to to.
setDidChange
Section titled “setDidChange”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.
The state
Section titled “The state”String* state(void)bool isIn(String* state)setState
Section titled “setState”void setState(String* state)Puts the machine in state without a transition and forgets the history: a
start or a reset.
Driving
Section titled “Driving”bool fire(String* event)Moves if the current state has a transition for event, and reports whether it
did.
canFire
Section titled “canFire”bool canFire(String* event)targetOf
Section titled “targetOf”String* targetOf(String* event)Where event leads from the current state, or null.
events
Section titled “events”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 6502How many moves back can undo.