for
The for loop is used to execute a block of code for each element in a collection.
Most commonly, you would use it with a Range or RangeInclusive to iterate over a sequence of numbers:
for x in Range(0, 5) {
Transmission { %(x) }
}
// Outputs 0, 1, 2, 3, 4
Loop Variables
The for loop variable can be declared as a context variable by prefixing it with use:
pub fn Example() {
for use x in Range(0, 5) {
TakeXFromContext
}
// Outputs 0, 1, 2, 3, 4
}
pub fn TakeXFromContext([x]) {
Transmission { %(x) }
}
You can provide two loop variables to iterate over the index and value of an Array:
let list = ["Potato", "Tomato", "Banana"]
for index, value in list {
Transmission { %(index + ": " + value) }
}
// Outputs "0: Potato", "1: Tomato", "2: Banana"
You can also iterate over the keys and values of a map using two loop variables:
let map = { potato = 123, banana = 456 }
for key, value in map {
Transmission { %(key + ": " + value) }
}
// Outputs "$potato: 123", "$banana: 456"
Returning Values
When for is used in an expression, the break statement determines the resulting value of the expression.
If the loop exists without a break, the resulting value will be undefined.
let list = [1, 2, 3, 4, 5]
let a = for x in list {
if x == 3 {
break 100
}
}
// a is either `100`