Skip to content

Repeat Statement

IsaacShelton edited this page Mar 21, 2022 · 1 revision

Repeat Statement

Repeat statements are used to execute a block of code a certain number of times

repeat count {
    // ...
}
repeat(count){
    // ...
}
repeat count,  // ...
repeat count   // ...
repeat(count)  // ...
repeat(count), // ...

They are very similar to traditional for-loops

for(idx usize = 0; idx < count; idx++) {}

is equivalent to

repeat count {}

idx

Inside of repeat statements, exists idx, which is a mutable reference to the current iteration index

idx

idx will be a usize in the range [0, count) and is incremented after every iteration

Execution Condition

Until the idx of the repeat loop reaches or exceeds the specified count, the block will be executed

Count Evaluation

By default, the count expression is re-evaluated before each iteration.

x int = 100
repeat x {
    print("This will only run once!")
    x = 0
}
This will only run once!

If this is undesired, it can be disabled by inserting the static keyword after repeat. When repeat static is used, then the count expression will only be evaluated once.

x int = 3
repeat static x {
    print("This will run all three times!")
    x = 0
}
This will run all three times!
This will run all three times!
This will run all three times!

Usage example

import basics

func main {
    repeat 5, print(idx)
}
0
1
2
3
4

Break and Continue

Both break and continue apply to repeat statements

Loop Labels

Loop labels can be used for repeat loops by specifying a name for the loop label followed by : before the count

repeat counting_to_ten : 10 {
    if idx == 6, break counting_to_ten
}

Renaming idx

You can use a different name instead of idx inside of repeat loops by putting after the count condition the using keyword followed by a different name

repeat 10 using i {
    printf("%d\n", i)
}
Clone this wiki locally