For loop

Simple loop

Syntax

for <init>, <end> <body>

  • init is an initializer, explained below

  • end is an expression, the value which initial variable iterates through to

  • body is a statement

The initializer

It could be:

A variable declaration

for var i = 0 ...
for let j = 0 ...

Use

A assign expression

var i = 0
for i ...

If the target vairable in the assignment is not defined, it will be defined by the let keyword implicitly.

for j = 0 ...
// like: for let j = 0 ...

Examples

Counting numbers

for i = 1, 10 {
    puts i
}

Printing even numbers

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

Counting down

for i = 20, 1 {
    puts i
}

C-style loop

But no parenthese, comma instead of semicolon.

Syntax

for <init>, <cond>, <updater> <body>

  • init is loop initializer, it could be an expression

  • cond is loop condition, an expression

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

Examples

Basic

for i = 0, i < 5, i++ {
    // do something
}

Without updater

for i = 0, i < 5, {
    i++ // own updater
}

If the last comma is removed, the loop becomes Simple loop.

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:

var arr = [1, 2, 3]
for v, i : arr {
    puts v, i    // value - index
}

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

for v : arr {
    puts v
}

With a map:

var map = { a: 4, b: 5, c: 6 }
for k, v : map {
    puts k, v    // key - value
}

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

So the output of above example could be:

a   4
b   5
c   6

... or

b   5
c   6
a   4

Like array, just get the key only:

for k : map {
    puts k
}

Infinite loop

Pure

for {
    // Do something
}

With initializer

for i = 1 {
    puts i++
}

Last updated