-
-
Notifications
You must be signed in to change notification settings - Fork 9
Each in Statement
Each-in statements are used to execute a block of code for each element in an array-like value
each ElementType in array_like {
// ...
}
each ElementType in array_like, // ...
each ElementType in array_like // ...
each ElementType in [pointer_to_values, count] {
// ...
}
each ElementType in [pointer_to_values, count], // ...
each ElementType in [pointer_to_values, count] // ...
Inside of each-in statements, exists it, which is a mutable reference to the current element
it
it will be a mutable reference to the current element
Inside of each-in 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 each-in loop reaches or exceeds the specified count, the block will be executed
By default, the count expression and array value are re-evaluated before each iteration.
If this is undesired, it can be disabled by inserting the static keyword after in. When each ElementType in static is used, the count expression and array value will both only be evaluated once.
each String in static getNames() {
print("Hello " + it + "!")
}
import basics
func main {
integers <int> List
integers.add(3)
integers.add(103)
integers.add(43)
integers.add(74)
each int in integers {
printf("Value of integers[%zu] is %d\n", idx, it)
}
}
Value of integers[0] is 3
Value of integers[1] is 103
Value of integers[2] is 43
Value of integers[3] is 74
Both break and continue apply to each-in statements
Loop labels can be used for each-in loops by specifying a name for the loop label followed by : before the element name/type
each every_swordfish_loop : swordfish Swordfish in swordfish_list {
if swordfish.didJustDie() {
swordfish_list.remove(idx--)
break every_swordfish_loop
}
}
Additional types can be allowed to be used with each-in loops by defining the __array__ and __length__ methods for the type in question.
import basics
struct DummyArrayLike (value int) {
func __array__ *int = &this.value
func __length__ usize = 1
}
func main {
array DummyArrayLike
array.value = 10
each int in array, printf("array[%zu] => %d\n", idx, it)
}
array[0] => 10