Skip to main content

Looping & Iteration

Coco only supports iteration over finite sequences (arrays, varrays) to prevent infinite loops. while and loop are not supported.

For Loops

Iterate over sequences with for:

memory items = []String{"foo", "bar", "baz"}

// Index and value
for idx, value in items:
items[idx] = value.ToUpper()

// Index only
for idx in items:
process(items[idx])

// Value only (use _ to skip index)
for _, value in items:
process(value)

Break & Continue

Control loop execution:

for idx, value in items:
if value == "stop":
break // Exit loop entirely

if value == "skip":
continue // Skip to next iteration

process(value)

Range

Enumerate over a sequence of numbers:

// Iterate 0 to 4
for i in range(5):
sum += i

// Result: sum = 0 + 1 + 2 + 3 + 4 = 10

// range(count, start) — count elements starting at start
for i in range(2, 5): // iterates over [5, 6]
sum += i
for i in range(5, 2): // iterates over [2, 3, 4, 5, 6]
sum += i
note

range(n) generates [0, 1, ..., n-1]. range(count, start) generates count elements starting at start.

Iterating Strings and Bytes

You can iterate over characters in a string or bytes in a byte sequence:

memory cnt U64
for i, c in "ABBA":
if c == "A":
cnt++
// cnt = 2

for i, b in Bytes(0xaabb):
// b is a single-byte Bytes value

Iterating an empty collection is safe — the loop body never executes.

Example

function CountUntil(items []String, target String) -> (count U64):
count = 0
for _, value in items:
if value == target:
break
count += 1