-
-
Notifications
You must be signed in to change notification settings - Fork 9
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 {}
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
Until the idx of the repeat loop reaches or exceeds the specified count, the block will be executed
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!
import basics
func main {
repeat 5, print(idx)
}
0
1
2
3
4
Both break and continue apply to repeat statements
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
}
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)
}