Switch Statement

From Second Life Wiki
Jump to navigation Jump to search

The switch case statement is a common programming construct used in many programming languages to check the value of a variable and execute different code blocks based on the value. However, in LSL, there is no built-in switch case statement.

Instead, scripters can achieve similar functionality using if-else statements or a series of if statements. This example will explain how to use if/if-else/else statements as an alternative to the switch case statement in LSL.

Examples

default{
  listen(integer channel, string name, key id, string message){

    if(message=="1"){
      llOwnerSay("The case is 1.");
    }
    else if(message=="2"){
      llOwnerSay("The case is 2.");
    }
    else if(message=="3"){
      llOwnerSay("The case is 3.");
    }
    else{
      llOwnerSay("The case is"+message+".");
    }
    //Only one of the statements will be accepted and ignores the rest.
    //Script can continue further in this event scope without the use of 'return'.
  }
}

Alternatively, using 'return' call to "break" out of the current scope. If the first condition is true, the second condition won't be evaluated, like a "switch" would do. Second "if" will be executed only if the first condition is false. Using "else" in this structure may not reach the same result.

default{
  listen(integer channel, string name, key id, string message){
    
    if(channel == PUBLIC_CHANNEL){
      llOwnerSay("The message was sent on Public Channel.");
      return;
    }      

    if(channel == DEBUG_CHANNEL) {
      llOwnerSay("The message was sent on Debug Channel.");
      return;
    }
  }
}

A JIRA feature request exists at VWR-1287. (Has been closed.)