> For the complete documentation index, see [llms.txt](https://aup.nomi.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://aup.nomi.dev/the-language/control-flow/for-loop.md).

# For loop

## Simple loop

### Syntax

`for <init>, <end> <body>`

* `init` is an **initializer**, explained [below](/the-language/control-flow/for-loop.md#the-initializer)
* `end` is an expression, the value which initial variable iterates through to
* `body` is a statement

### The initializer

It could be:

#### A variable declaration

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

Use&#x20;

#### A assign expression

```javascript
var i = 0
for i ...
```

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

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

### Examples

#### Counting numbers

```lua
for i = 1, 10 {
    puts i
}
```

#### Printing even numbers

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

#### Counting down

```lua
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

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

#### Without updater

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

{% hint style="warning" %}
If the last comma is removed, the loop becomes [**Simple loop**](/the-language/control-flow/for-loop.md#simple-loop).
{% endhint %}

## 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:

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

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

```javascript
for v : arr {
    puts v
}
```

With a map:

```javascript
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:

```javascript
for k : map {
    puts k
}
```

## Infinite loop

#### Pure

```javascript
for {
    // Do something
}
```

#### With initializer

```javascript
for i = 1 {
    puts i++
}
```
