# Loops

## While loops

Syntax:

    while <expression1> do <expression2>
    until <expression1> do <expression2>
    do <expression2> while <expression1>
    do <expression2> until <expression1>

These are similiar to other languages, however they return the result of the last iteration or `NULL` if no iteration was done. In the boolean expression, `=` is translated into `==` just as for the `if` statement.

## For loops

Syntax:

    for <identifier> = <from> to <to> do <body>
    for <identifier> = <from> to <to> by <increment> do <body>

Loop with identifier being set to all values from `<from>` to `<to>`, optionally using an increment other than 1. These are faster, nicer and more compact than the normal loops such as above, but less flexible. The identifier must be an identifier and can't be a dereference. The value of identifier is the last value of identifier, or `<from>` if body was never evaluated. The variable is guaranteed to be initialized after a loop, so you can safely use it. Also the `<from>`, `<to>` and `<increment>` must be non complex values. The `<to>` is not guaranteed to be hit, but will never be overshot, for example the following prints out odd numbers from 1 to 19:

    for i = 1 to 20 by 2 do print(i)

## Foreach loops

Syntax:

      for <identifier> in <matrix> do <body>

For each element, going row by row from left to right do the body. To print numbers 1,2,3 and 4 in this order you could do:

    for n in [1,2:3,4] do print(n)

If you wish to run through the rows and columns of a matrix, you can use the RowsOf and ColumnsOf functions which return a vector of the rows or columns of the matrix. So,

    for n in RowsOf ([1,2:3,4]) do print(n)

will print out [1,2] and then [3,4].

## Break and continue

You can also use the `break` and `continue` commands in loops. The continue `continue` command will restart the current loop at its next iteration, while the `break` command exits the current loop.

    while(<expression1>) do (
      if(<expression2>) break
      else if(<expression3>) continue;
      <expression4>
    )