LSL Wiki Mirror 10-5-2006: IfElse

HomePage :: PageIndex :: RecentChanges :: RecentlyCommented :: UserSettings ::

If-Else


Execute some statement(s) if a condition is true, else some other statement(s) if it is false.

Format:
if (condition)
        statement
else
        statement

if (condition)
{
	statements
}
else
{
	other statements
}

Notes:


Syntax


There are no semicolons at the end of the conditional statement.

Incorrect Example
if (condition);
{
	statement;
}

if (condition);
{
	statement2;
}

Using a semicolon after the if statement will cause the code inside the curly braces to execute regardless of the result of the conditional statement.

Example:
if (llFrand(1.0) > 0.5)
    llSay(0, "heads");
else
    llSay(0, "tails");

This code checks to see if a random number between 0.0 and 1.0 is greater than 0.5. If it is, the script says "heads", if it's not, the script says "tails"

Note: Only up to 23 else statements may be in a conditional chain. (a total of 24 conditionals: 1 if and 23 elses) Any more, and a syntax error will occur when the script is saved/compiled. However, a workaround to this is to nest conditionals, or, if that's not possible, split the conditional chain into a series of distinct if statements: at the end of each if(){} block, put a jump or return as the last statement so that the remaining if statements that would have otherwise been "else if" statements are skipped.


Boolean Operators


By using boolean operators to AND or IF conditions together, code will be more efficient and use less memory than it would otherwise. Suppose a variable i is FALSE and another variable j is TRUE:

Compare this:
integer i = FALSE;
integer j = TRUE;

if (i)
{
    // we will not reach here.
}
else if (j)
{
    llOwnerSay((string)llGetFreeMemory());
}

And this:
integer i = FALSE;
integer j = TRUE;

if (!i)
{
    if (j)
    {
        llOwnerSay((string)llGetFreeMemory());
    }
}

To this:
integer i = FALSE;
integer j = TRUE;

if (!i && j ) // if i equals FALSE AND j equals TRUE.
    llOwnerSay((string)llGetFreeMemory());

See?

Note: In some other languages, one must formally end the IF statement with endif or something similar. LSL does not.


Script | Flow Control
There are 13 comments on this page. [Display comments/form]