LSL Code Structure

By Xah Lee. Date: .

All scripts, have the following simple structure: They are a sequence of blocks called “states”. Inside each State block, is a sequence of code blocks called “event handlers”. And inside each event handler, is a sequence of “functions”.

Here's a example showing the overall structure:

State A {
  Event Handler 1 { do this, do that, …}
  Event Handler 2 { do this, do that, …}
  …
}

State B {
  Event Handler 1 { do this, do that, …}
  Event Handler 2 { do this, do that, …}
  …
}

…

Each object at any give time is always in one of the state as defined in the script. When a event occurs, for example, when a object is touched, pushed, in a particular position, or being sit on or talked to, the event handler in the current state will be called, and the functions inside the event handlers tells the object what to do. For example, it may play a sound, emit particles, play video, send a message, set variables, do some computation, switch to another state, etc.

Here's a actual code example. Try to see the nested structures of (states (event-handlers (functions))).

// A script that toggles the prim from color Red and Black, when touched. 

// default state
default
{
     state_entry()
     {
         llSay(0, "i'm on!");
         llSetColor(<1,0,0>, ALL_SIDES); // sets all sides to red
     }

     touch_start(integer total_number)
     {
         state off;
     }
 }

// another state
state off
{
    state_entry()
    {
        llSay(0, "i'm off!");
        llSetColor(<0,0,0>, ALL_SIDES);
    }

    touch_start(integer total_number) 
    {
        state default;
    }
}

In the above code, the default is the name of a predefined state called default state. All code must have the default state, and it is the initial state of the object. All other states are named like state name_of_state { … }.

The state_entry is the initial event handler. It is invoked when the state is activated. The touch_start is another event handler. It is invoked when the object is touched.

The llSay, llSetColor are all functions. They specify what to do.

The above explains the important hierarchical forms in all lsl source code.

By the way, “state off” and “state default” in the above code, are state switching statements. To switch from one state to another, just use call state new_state_name;.

In vast majority of scripting, you do not need to define multiple states. If you want states, it is much easier to use a global variables for that purpose. So, most of your code will look like this:

// global variables here

// function definitions here

// main
default
{
     state_entry()
     {
         // setting variables and function calls here
     }

     // more event handler here
}

Continue to simple Script Examples.