jeffheaton's picture

    The concept of a state machine is not unique to Second Life. State machines are a common programming paradigm. However, no language makes the concept of a state machine as integral as the Linden Scripting Language. Many of the recipes in this book use state machines. As a result, it is very important to understand the concept of a state machine.

    To see state machines in action, consider the default script, which is automatically generated by Second Life, when a new script is created. This script is shown here.

default
{
    state_entry()
    {
        llSay(0, "Hello, Avatar!");
    }

    touch_start(integer total_number)
    {
        llSay(0, "Touched.");
    }
}

    This script starts with the word default. The word default specifies the name of the state that the enclosed code belongs to. For this script there is only one state. This state, which is named default, is the starting state for any script in Second Life.

    Many scripts are constructed entirely within their default state. This is often bad design in Second Life. Consider the following script, which implements a simple switch that can be turned on or off.

integer value;

default
{
    state_entry()
    {
        value = TRUE;
    }

    touch_start(integer total_number)
    {
        if( value==TRUE ) 
        {
            llSay(0,"On");
            value = FALSE;
        }
        else
        {
            llSay(0,"Off");
            value = TRUE;
        }
    }
}

    As can be seen, a global variable, named value, is set to either TRUE or FALSE. As the user touches the object, the object will say either “On” or “Off”. As the object is touched these values alternate. Also, a note on global variables. Global variables are normally considered bad programming practice. However in Second Life, there is really little choice as to whether to use them or not. Because the Linden Scripting Language does not support user defined classes, global variables are the primary way for a script to hold values long-term.

    This same functionality could be created using a state machine. The following lines of code do this.

default
{
    touch_start(integer total_number)
    {
        llSay(0,"On");
        state off;
    }
}

state off
{
    touch_start(integer total_number)
    {
        llSay(0,"Off");
        state default;
    }
}

    The above code creates a second state, named off. This gives the above script two states: default and off. Both states contain their own touch_start event. Both states use the state command to switch to the opposite state when the object is touched.

    The Linden Scripting Language is optimized for state engines. Because of this, state engines should be used when possible.


Copyright 2005 - 2012 by Heaton Research, Inc.. Heaton Research™ and Encog™ are trademarks of Heaton Research. Click here for copyright, license and trademark information.