Talk:LSL Switch Statement

From Second Life Wiki
Jump to navigation Jump to search

Speaking from experience, implementing a switch statement is within the purview of the compiler's parser and code-generator. To implement such requires only comparison and both conditional and unconditional branching support within the Sim's interpreter. The same applies to break and continue statements as well. Num Skall

The VM supports those opcodes already. The bytecode for something like

switch (variable)
{
    case condition_1:
        a;
        break;
    case condition_2:
        b;
    default:
        c;
}

would be...

variable;
DUP
PUSH condition_1
EQ
JUMPNIF case2
a;
JUMP end
@case2
DUP
PUSH condition_2
EQ
JUMPNIF default
b;
@default
c;
@end
POP

An important thing to remember is that there is an extra variable on the stack that needs to be popped off. So if return or state are used in a switch statement then the condition needs to be popped off. You can't just keep calling 'variable' as it may be a function that returns a different value for each call. See: [1] for info on the assembly used.

The above assembly is essentially the same as the below but without the stuff being done with DUP, though if LSL's compiler was optimizing it could come up with the above bytecode.

var t = variable;
if(t == condition_1)
    a;
else
{
    if(t == condition_2)
         b;
    c;
}