LSL States

From Second Life Wiki
Revision as of 10:59, 22 September 2011 by Strife Onizuka (talk | contribs)
Jump to navigation Jump to search

In LSL, most scripts sit idle until they receive some input, or detect some change in their environment. At any moment, the script is in some state, and will react to events or inputs according to some scheme defined by the programmer. However, a script can also contain two or more different states, and react differently to events or inputs depending on what state it is in.

One common abstract model that is used in such cases is called a Finite State Machine (see Wikipedia[1])].

For example, a door might be in a waiting state, and ignore all inputs except being touched. Once touched, it goes to the open state, in which it ignores being touched, but monitors which avatars pass through it. After a while, it changes to the closing state during which it closes, and then it returns to the waiting state.

States are not the only way to represent this kind of behavior, but in some cases they are a very good way.

In LSL, a state is a specified section of code within which all Events are specified. The main state that is required by all LSL scripts is called default; all scripts must have a default state, and every state must have at least one event.

To add another state add an entry like this: <lsl> state my_state {

   state_entry()
   {
       // What should happen when we enter this state
   }
   // other events and code

} </lsl>

To switch from one state to another add a line like this:

<lsl> state my_state; </lsl>

When this line of code is executed, it will run anything in the state_exit event, and then switch to the new state.

When switching states, all event queues are cleared, and events requiring setup are disabled such as timer, sensor, and listen.

The state_entry event is run when the code enters that state. There is sometimes confusion in thinking that the state_entry event will run when a scripted object is rezzed from inventory. This is not the case as scripts are frozen when taken into inventory in the state they are in, and resume operation in that state when rezzed. The event first called when an object is rezzed out of inventory is on_rez.

See also

For more information, see State.