For statement

Simple loop

for initializer[, end] {
    // statements
}
  • initializer is a part of variable declaration

  • end is the limit which loop variable reach to

Counting numbers

for i = 1, 10 {
    puts i
}

The variable i be declared implicitly, and belong to the loop scope.

Printing even numbers

for i = 0, 20 {
    if i % 2 == 0 {
        puts i
    }
}

Counting down

C-style loop

But no parenthese, comma instead of semicolon.

  • initializer could be an expression

  • cond is loop condition, an expression

  • updater is an expression, which is executed after the loop body

Basic

Without initializer

Without updater

For-each loop

Iterating through an array, map.

Syntax

for <first> [, <second>] : <expr> <body>

  • first - the first variable

  • second - the second variable (optional)

  • expr - an expression to be evaluated, value must be a map or an array

Examples

With an array:

Just use for v : arr to get the value only.

With a map:

Depend on the implementation, the key - value pairs may not in input order.

So the output of above example could be:

... or

Like array, just get the key only:

Infinite loop

Pure

Just use for without any option.

With initializer

Consider before using the infinite loop, that will make your program gets stuck.

Last updated

Was this helpful?