Looping through Sequences
Cocolang restricts loop structures to prevent unbound loops that can execute infinitely. This means loop forms such as do
and do while
are not supported.
Instead, all looping is performed by iterating over sequence types like Arrays and Varrays, which may be large but still finite.
The for
statement can be used to loop through sequence type. It receives the index and the value from the sequence for each iteration. Variables declared in the for statement are new declarations and only exist within the loop's scope.
Enumeration with Range
Simple enumerating loops such as iterating over a sequence of numbers which is usually performed using a construct like for i=0;i<n;i++
, is instead achieved in Coco using the range
keyword. This internally creates a varray of the given size and iterates over it.
Optional Iterator Elements
Loop constructs generally have two iteration elements, one for the iteration index and the other for the value at that index. Not all loops require both values so we can skip one of them, if not required.
- If both iterator elements are required, we use
for index, value in x
- If only the index is required, we use
for index in x
. This is the syntax we generally use for therange
style loops - If only the value is required, we use
for _, value in x
.
Break & Continue
The break
and continue
statements can be used to exit the loop or skip the current iteration respectively. They work as illustrated in Loop.BreakContinue()
coco Loops
func Simple():
memory sequence = []String{"foo", "bar", "boo", "far"}
for idx, value in sequence:
sequence[idx] = value.ToUpper()
func Optional():
memory sequence = []String{"foo", "bar", "boo", "far"}
for _, value in sequence:
if value.IsUpper():
return
func Range() -> (sum U64):
for i in range(5):
sum += i
func BreakContinue() -> (filtered []U64):
for number in range(10):
if number%2 == 0:
continue
if number == 9:
break
append(filtered, number)