11: Loops (For, Foreach, While Do while) [✓] - royal-lang/rl GitHub Wiki

There are 3 different types of loops in Royal. For loops, foreach loops, while / do-while loops.

For Loops

A for loop is a loop that will keep iterating until a condition is met but additionally allows for a pre-initialization of a variable that can be created and used within the scope of the loop, as well a post-expression that can be used to ex. increment the variable created.

Parentheses for the for loop are optional.

for (PRE_INITIALIZATION, CONDITION, POST_EXPRESSION) // Or just: for PRE_INITIALIZATION, CONDITION, POST_EXPRESSION
{
    ...
}

Example:

for (var i = 0, i < 10, i++)
{
    writeln(i);
}

Foreach Loops

A foreach loop is a type of loop that iterates over a range of elements or values.

There are three types of foreach loops in Royal. A single value iteration loop, a range loop and a key-value loop.

Just like for loops then parentheses are optional.

foreach (VALUE, ITERATABLE_ELEMENTS) // ITERATABLE_ELEMENTS are ex. arrays, ranges etc. Or just: foreach VALUE, ITERATABLE_ELEMENTS
{
    ...
}

foreach (INDEX, FROM .. TO) // FROM and TO must be integers.
{
    ...
}

foreach (KEY,VALUE, ITERABLE_ELEMENTS) // ITERABLE_ELEMENTS are ex. arrays, associative arrays etc.
{
    ...
}

Example:

var array = [1,2,3,4,5];

foreach (item, array)
{
    writeln(item);
}

foreach (i, 0 .. array.length)
{
    var item = array.get(i);

    writeln(item);
}

var aa = ["First Number": 1, "Second Item": 2];

foreach (k,v, aa)
{
    writefln("Key: %s, Value: %d", k, v);
}

While Loops / Do-while Loops

While loops are loops that will run while a condition is met, whereas do-while loops are similar but will initially run even if the condition isn't met.

Just like for loops and foreach loops then parentheses are optional.

The condition can be omitted from the loop which will basically be an infinite loop instead of having to do while true / while 1 etc.

while (CONDITION) // Or just: while CONDITION
{
    ...
}

do
{
    ...
} while (CONDITION);

Example:

var i = 0;
while i < 10
{
    writeln(i);

    i++;
}

do
{
    writeln(i);

    i++;
} while i < 10;