Skip to main content

Looping & Iteration

Looping through Sequences

Coco restricts loop structures to prevent unbound loops that can execute infinitely. This means loop forms such as loop or 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.

coco Loops

function Simple():
memory sequence = []String{"foo", "bar", "boo", "far"}

for idx, value in sequence:
sequence[idx] = value.ToUpper()

memory count_until_bar U64
for idx in sequence:
if sequence[idx] == "BAR":
break
count_until_bar += 1

memory not_far U64
for _, value in sequence:
if value == "FAR":
continue
not_far += 1

Enumeration with Range

function Range() -> (sum U64):
memory s = 0
for i in range(5):
s += i
sum = s

Simple enumerating loops such as iterating over a sequence of numbers is achieved in Coco using the range keyword. This internally creates a varray of the given size and iterates over it, so both index and value are the same.

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 the range 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.