Loops

While Loops

Syntax:

while <expression1> do <expression2>
until <expression1> do <expression2>
do <expression2> while <expression1>
do <expression2> until <expression1>
These are similar to other languages. However, as in gel it is simply an expression that must have some return value, these constructs will simply 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 in the matrix, going row by row from left to right we execute the body with the identifier set to the current element. 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>
)