State machine shorthand: $provide and $reference

From Tekkotsu Wiki

Jump to: navigation, search

Contents

This article is part of the State Machines series.

The state machine shorthand includes a mechanism for a parent node to provide variables that child (grandchild, etc.) nodes can reference.

The $provide directive

  • The $provide directive goes in the parent node's class definition, and acts as a variable declaration. An optional initial value may be supplied in parentheses.
  • You must use $nodeclass (rather than a pure C++ class declaration) to define the parent class in order to use $provide.
  • Example of a $provide directive:
          $provide unsigned int x(5), float y;

The $reference directive

  • The $reference directive goes in each of the child nodes' methods that needs access to that variable. The variable name must be qualified by the parent's class, e.g., Mama::x.
  • In order to use $reference directives in a class's methods, the class must be declared inside the parent class.
  • Example of a $reference directive:
            $reference Mama::y;

Sample program

The program below is a complete example which you can compile and run:

#include "Behaviots/StateNode.h"

$nodeclass Mama : StateNode {
  $provide unsigned int x(5), float y;

  $nodeclass Sonny : StateNode : doStart {
    $reference Mama::x, Mama::y;
    cout << "Sonny says x = " << x++ << endl;
    y = sqrt(x);
  }

  $nodeclass Princess : StateNode : doStart {
    $reference Mama::y;
    cout << "Princess says y = " << y << endl;
  }

  $setupmachine{
    startnode: Sonny =N=> again: Sonny =N=> onemore: Sonny =N=> Princess
  }

}

REGISTER_BEHAVIOR(Mama);

Additional Informtation

Shared variables are just one of the three mechanisms that can be used to transmit information among state nodes. The other two are SignalTrans transitions, and static variables. See the article on State machine communication for more information.