thp-lang.org/md/learn/flow-control/loops.md
2024-03-28 19:46:23 -05:00

960 B

Loops

For loop

Braces are required.

val numbers = [0, 1, 2, 3]

for number in numbers
{
    print(number)
}

for #(index, number) in numbers.entries()
{
    print("{index} => {number}")
}
val dict = .{
    apple: 10,
    banana: 7,
    cherries: 3,
}

for #(key, value) in dict
{
    print("{key} => {value}")
}
for value in collection
{
    if condition
    {
        break
    }
}

While loop

val colors = ["red", "green", "blue"]
val mut index = 0

while index < colors.size()
{
    print("{colors[index]}")
    index += 1
}

Infinite loop

Instead of doing while true {} use loop.

loop
{
    print("looping")

    if condition
    {
        break
    }
}

Labelled loops

You can give labels to loops, allowing you to break and continue in nested loops.

:top for i in values_1
{
    for j in values_2
    {
        // ...
        break :top
    }
}