Flow control
if( a > 5 )
{
println( "'a' is greater than 5" );
if( a < 10 )
println( "...but less than 10" );
}
else
println( "'a' is not greater than 5" );
- It is possible to only run code if a certain condition is true, using the
if
statement.
- If/else statement has the following syntax:
if ( <expression> ) <statement>
, optionally followed by else <statement>
{ .. }
is a block statement, it can be used anywhere a statement can be used
>
("greater than") is one of 8 comparison operators. The others are:
<
- "less than"
>=
- "greater or equal"
<=
- "less or equal"
==
- "equal"
!=
- "not equal"
===
- "strict equality" (not only value must be equal, types must also be same)
!==
- "strict inequality" (inverse of strict equality)
- These operators are not limited to
if
and other such statements, they can be used as any other operator.
- These operators return the type
bool
, it has only two values - true
and false
while( a > 5 )
{
println( a );
--a;
}
for( i = 0; i < 5; ++i )
println( i );
- There are 6 kinds of loops in SGScript:
- The 'while' loop:
while ( <expression> ) <statement>
- The 'for' loop:
for ( <expression-list> ; <expression> ; <expression-list> ) <statement>
- It is a shortcut for a while loop where first expression/list is run before the loop, second - as the condition, third - before each jumpback.
- The 'do-while' loop:
do <statement> while ( <expression> )
- The 'foreach-value' loop:
foreach ( <nvalue-ame> : <expression> ) <statement>
- The 'foreach-key' loop:
foreach ( <key-name> , : <expression> ) <statement>
- The 'foreach-key-value' loop:
foreach ( <key-name> , <value-name> : <expression> )
foreach( name : [ "one", "two", "three" ] )
println( name ); // prints one, two, three
foreach( key , : _G )
println( key ); // prints names of all global variables
foreach( key, value : myObject )
{
if( string_part( key, 0, 2 ) == "!_" )
println( value ); // print all values for keys beginning with "!_"
}
foreach
loops give read-only values (they can be written to but source will not be updated).
foreach( value : data )
{
if( value === false )
continue;
if( value )
break;
}
- It is possible to stop loop execution with
break
or jump to the next iteration with continue
.
break
will skip to code right after the loop.
continue
will skip to right before the end of the loop.
- It is also possible to specify the loop number (within the function/global scope, counting from innermost, starting at 1) to go to.