State machine structure

From Tekkotsu Wiki

Jump to: navigation, search

State machines are hierarchically organized collections of state nodes and transitions.

A typical user application consists of a parent node class containing definitions for all the node classes needed for the state machine, and a setup() method that constructs the child nodes and transitions that make up the machine. One of these children is designated the start node. The parent's doStart() method simply calls the start node's doStart() method.

Rather than writing the class definitions and setup() method directly, which can be tedious and error-prone, users describe their state machines using a shorthand notation that is turned into C++ code by Tekkotsu's state machine compiler. The notation includes directives for defining new node types ($nodeclass), setting up a state machine ($setupmachine or $statemachine), and sharing variables among state nodes ($provide and $reference). Here is an example of a typical state machine definition:

#include "Behaviors/StateNode.h"

$nodeclass ConversationMachine : StateNode {

  $nodeclass SayHi : StateNode : doStart {
    cout << "Hi there!" << endl;

  $nodeclass SayBye : StateNode : doStart {
    cout << "Bye now." << endl;

    SayHi =N=> SpeechNode($,"Lovely day, isn't it?") =C=> adieu: SayBye



In the above example, the parent node class is ConversationMachine. Its three children, created by its setup() method, will be instances of the SayHi, SpeechNode, and SayBye classes. Because only the third child was assigned an explicit name when it was defined, the others receive default names, so the children's names will be sayhi1, speechnode1, and adieu.

To read more about the $nodeclass directive, see the article State machine shorthand: class definitions. To read about the shorthand used in $setupmachine, see the article on State machine shorthand: transitions.

The setup() Method

$setupmachine is actually shorthand for a $statemachine directive wrapped in a setup method definition. Thus, the $setupmachine expression in the example above could have been written as:

  virtual void setup() {
      SayHi =N=> SpeechNode($,"Lovely day, isn't it?") =C=> adieu: SayBye

State Node Instantiation Syntax

The full syntax for instantiating a state node is:

label: ClassName`(args)[inits]
  • label must begin with a lowercase letter
  • ClassName must be the name of a class that inherits from StateNode, and must begin with a capital letter
  • The optional backquote character, if present, indicates that the node should speak its name when it fires (for debugging)
  • args is a list of constructor arguments; only used if the node's constructor accepts arguments
  • inits (rarely used) is a sequence of intializer expressions, separated by semicolons, to be executed when constructing the node