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:
- The else and its statements are optional.
- If there's only one statement in the block of code then the encompassing curly braces ('{' and '}') are also optional.
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:
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:
And this:
To this:
See?
Note: In some other languages, one must formally end the
IF statement with
endif or something similar. LSL does not.
Script |
Flow Control