Loops

Moth uses one loop keyword for conditional repetition, collection iteration and numeric ranges. The header selects the form, so you don't need separate while, for and range-loop keywords.

break and continue target the nearest loop. A by step is signed, so its sign chooses direction rather than the bounds. Range bounds and steps follow the exact numeric rules rather than backend-native arithmetic.

Choose the explanation level: Conditional loops

Conditional loops

A conditional loop keeps repeating while a condition is true.

The condition is checked before each trip through the loop. This means the body might not run at all.

count ~= 0

loop count < 3:
    io.line([: Count: [count]])
    ~count += 1
;

This prints three lines. Once count < 3 becomes false, the loop ends and the program continues after it.

Make sure the condition can change

A condition that never becomes false keeps the loop running forever.

running ~= true

loop running:
    do_some_work()

    if work_is_finished():
        ~running = false
    ;
;

Use a conditional loop when repetition depends on a changing state rather than a collection or a known numeric range.

Moth uses one loop keyword for conditional loops, collection iteration and numeric ranges.

A conditional loop evaluates a Bool condition before each iteration and runs its body while that condition remains true.

count ~= 0

loop count < 3:
    io.line([: [count]])
    ~count += 1
;

Conditional loop contract

  • The form is loop condition: ... ;.
  • An inline loop closes on the line containing its opening :. A multiline loop closes with ; alone after its body. See Blocks and statements.
  • The condition must resolve to Bool.
  • The condition is checked before the first iteration, so the body may run zero times.
  • It is checked again after each completed iteration.
  • Conditional loops do not declare item or index bindings.
  • There is no separate while keyword.
  • break exits the nearest active loop.
  • continue skips the rest of the current body and starts the next condition check.

Divergence proof

A conditional loop whose condition has normalised to compile-time true and which has no reachable break targeting that loop diverges. Falling through the body or executing continue starts another iteration. A reachable break targeting the loop makes the post-loop continuation reachable. A nested loop consumes its own break and continue. A nested-loop break does not make an outer true loop escapable. Return and divergence pass outward.

Collection and range loops stay conservatively non-divergent because their iteration count is finite or may be zero.

This proof uses the ordinary folded Bool authority. It does not inspect a runtime condition to decide that the loop stays true forever.

Header classification

A top-level to marker makes the header a range loop.

Without a range marker, a top-level by step or an explicit |...| suffix marks a collection loop. Without bindings or a step, a collection-typed header is still a collection loop. Every other header must type-check as a Bool condition. A by step on a Bool condition is rejected instead of being treated as a collection loop.

Scope

The body is a child scope. Names declared inside it are not visible after the loop.

Choose the explanation level: Collection loops

Collection loops

A collection loop visits the values in a collection, from the first item to the last by default.

names = {"Priya", "Rob", "Emmy"}

loop names |name|:
    io.line([: Hello, [name]])
;

The name inside |...| is created for the loop body. On each iteration it refers to the current item.

Add an index when you need one

A second name receives the item's index in the source.

names = {"Priya", "Rob", "Emmy"}

loop names |name, index|:
    io.line([: [index]: [name]])
;

Without a step, the first item has index 0, the second has index 1 and so on. The index binding has type I32.

Visit every second item

Add by after the source to set a signed step.

names = {"Priya", "Rob", "Emmy"}

loop names by 2 |name, index|:
    io.line([: [index]: [name]])
;

This visits Priya at index 0 and Emmy at index 2. The index binding still reports the item's real position in the source.

A negative step starts at the last item and walks backwards. The step must be a signed whole number and cannot be zero.

Ignore the item when only the repetition matters

Bindings are optional.

items = {10, 20, 30}
count ~= 0

loop items:
    ~count += 1
;

After this loop, count is 3.

A collection loop visits values from a Moth collection. By default it walks from the first item to the last.

names = {"Priya", "Rob", "Emmy"}

loop names |name, index|:
    io.line([: [index]: [name]])
;

Forms of collection loops

loop items:
    ~count += 1
;

loop items |item|:
    inspect(item)
;

loop items by step:
    ~count += 1
;

loop items by step |item|:
    inspect(item)
;

loop items by step |item, index|:
    inspect(item)
;

Collection loop contract

  • The source expression must have a collection type.
  • Collection loops do not use a general iterable protocol.
  • Hash maps are not collection-loop sources.
  • Bindings are optional.
  • The first binding receives the current item and has the collection's element type.
  • The optional second binding receives the actual source index of the current item and has type I32. A stepped loop visits source indexes such as 0, 2 and 4, not ordinal positions.
  • Binding names are written inside one |...| suffix.
  • A binding list may contain one or two names.
  • An empty binding list, a third binding or duplicate binding names are invalid.
  • Loop bindings are immutable body-local names.
  • Binding an unresolved whole-number item pins its integer family, including whole-number leaves in a known nested item shape. Later integer receivers can still select its width, but float, decimal and Byte receivers or peers require an explicit cast.
  • A binding name must not collide with another visible name.
  • An empty collection with a non-zero step runs the body zero times.

Collection loop evaluation order

The source expression is evaluated once before iteration begins. The collection length is captured at the same point. An explicit step is then evaluated once.

The step is a signed fixed-width integer (I8, I16, I32 or I64) and keeps its own type. An omitted step is +1 with type I32, and an untyped whole-number literal step also defaults to I32. A step whose type is unsigned, binary-float, Byte or Dec is rejected. A zero step is invalid.

A positive step starts at index 0 and advances by the step while the index is below the captured length. A negative step starts at the last source index and advances by the signed step while the index remains at or above 0. An overshoot ends the loop without constructing an invalid index. With a non-zero step, an empty source visits nothing.

continue advances by the step. break exits the loop.

A literal zero step is rejected during compilation with MOTH-SYNTAX-0029. A dynamic zero step fails with built-in error code 306 (InvalidLoopStep) before the empty-source check.

stride_items = {10, 20, 30, 40, 50}

loop stride_items by 2 |item, index|:
    io.line([: [index]: [item]])
;

loop stride_items by -2 |item, index|:
    io.line([: [index]: [item]])
;

The first loop visits 10 at index 0, 30 at index 2 and 50 at index 4. The second loop visits 50 at index 4, 30 at index 2 and 10 at index 0.

Removed syntax

The old in form is not valid.

loop item in items:
    inspect(item)
;

Write the collection source first, then any by step, then bindings after it:

loop items by 2 |item|:
    inspect(item)
;

Progress records target support, including current HTML-Wasm collection limits, separately from these collection semantics.

Choose the explanation level: Range loops

Range loops

A range loop counts through numbers.

to stops before the end value:

loop 0 to 5 |value|:
    io.line([: [value]])
;

This produces 0, 1, 2, 3 and 4.

Use to & when the end value should be included:

loop 0 to & 5 |value|:
    io.line([: [value]])
;

This also produces 5.

Start from zero

You can leave out the first 0.

loop to 5 |value|:
    io.line([: [value]])
;

Change the step

Use by to set a signed step:

loop 0 to 10 by 2 |value|:
    io.line([: [value]])
;

This produces 0, 2, 4, 6 and 8.

Count downward

Use a negative step:

loop 5 to 0 by -1 |value|:
    io.line([: [value]])
;

This produces 5, 4, 3, 2 and 1.

The step's sign chooses direction. The bounds never do, so loop 5 to 0 visits nothing and loop 5 to & 0 by -1 includes 0. You do not need a reverse keyword.

Any range using F16, F32 or F64 needs an explicit float step:

loop 0.0 to 1.0 by 0.1 |amount|:
    io.line([: [amount]])
;

The value binding uses the selected range type. The optional second binding counts visited iterations from zero and always has type I32, even when the range counter uses another exact type.

Fixed-width bounds follow the exact numeric domain rules. Steps are signed whole numbers from I8 through I64. An omitted step is one, and unsigned, Byte, Dec or float steps do not apply to an integer range. A literal zero step is rejected during compilation. Any other zero step fails before the first iteration. Counter updates end at the last valid endpoint rather than overflowing.

A range loop generates numeric values directly from its loop header.

loop 0 to 10 by 2 |value, ordinal|:
    io.line([: [ordinal]: [value]])
;

Forms of range loops

loop start to end:
    ...

loop start to & end |value|:
    ...

loop start to end by step |value, ordinal|:
    ...

loop start to & end by step |value, ordinal|:
    ...

loop to end |value|:
    ...

loop to & end by step:
    ...

Bounds

  • to uses an exclusive end bound.
  • to & uses an inclusive end bound.
  • An omitted start is 0.
  • The bounds alone select the counter type.
  • There is no reverse keyword.
  • When start and end are equal, to produces no iterations and to & produces one.

Steps

by supplies a signed step. Its sign alone selects direction. A positive step counts upward, a negative step counts downward and a zero step is invalid. Bounds never infer direction, so a range whose step points away from its end bound is empty.

loop 5 to 0 by -1 |value|:
    io.line([: [value]])
;

loop 5 to 0 |value|:
    io.line([: [value]])
;

The first loop visits 5, 4, 3, 2 and 1. The second loop visits nothing.

Range bounds are exact fixed-width integers (I8 through U64) or binary floats (F16, F32 and F64). Byte, Dec and DecN have no range domain. Mixed bounds follow the exact numeric domain rules in Numbers. The selected range type is the counter domain, not a positional index type. The step never selects or widens that counter.

  • An omitted step on an integer range is 1 with type I32. An untyped whole-number literal step also defaults to I32.
  • An integer range accepts a step of type I8, I16, I32 or I64. The step keeps its own type.
  • A step whose type is unsigned, binary-float, Byte or Dec is rejected on an integer range.
  • A range using a binary float requires an explicit by step.
  • A float range accepts a binary-float step at the same or narrower precision than the counter, then converts it to the counter type. A wider float step is rejected. A typed integer step never becomes a float step, while an untyped whole-number literal step takes the counter precision.
  • Start and end expressions must have numeric types.
loop 0.0 to 1.0 by 0.1 |amount|:
    io.line([: [amount]])
;

loop 1.0 to & 0.0 by -0.5 |amount|:
    io.line([: [amount]])
;

Range loop evaluation order

Start, end and explicit step expressions are evaluated once, from left to right, before the first bounds check.

The loop keeps those evaluated values for the complete iteration.

A dynamic zero step fails before any bounds check, even when the range is empty or points in the wrong direction.

Bindings

The first binding receives the current range value in the selected exact counter type. The bounds alone select that type, and the step keeps its own type. Range counters keep their selected domain rather than inheriting a minimum width.

The optional second binding receives the zero-based iteration ordinal and always has type I32. It counts visited iterations upward, regardless of the counter value or direction. The counter domain and ordinal type remain independent. Collection lengths, collection indices and fixed capacities also use I32.

loop 5 to 0 by -1 |value, ordinal|:
    io.line([: [ordinal]: [value]])
;

This visits 5 at ordinal 0 through 1 at ordinal 4.

Bindings use the same one-or-two-name |...| rules as collection loops.

Checked updates

An integer range candidate uses exact arithmetic, and the counter is replaced only when that candidate still lies within the bound in the step's direction. A candidate that would pass the bound ends the loop, so the counter never needs a value outside its domain. An inclusive range exits after visiting its endpoint without computing a successor.

Termination also holds at the edges of the counter domain. An inclusive range ending at a type's maximum and a descending range reaching zero both complete normally. Distances up to U64::MAX stay exact, and a step at an I64 minimum keeps its full magnitude.

The I32 ordinal uses a checked integer update, so its own overflow remains an implicit failure.

near_max U8 = 254
maximum U8 = 255
loop near_max to & maximum by 1 |value, ordinal|:
    io.line([: [ordinal]: [value]])
;

This range visits 254 and 255 as U8 values. Its I32 ordinal runs from 0 to 1, and termination needs no U8 successor beyond 255.

A literal zero step is rejected during compilation with MOTH-SYNTAX-0029, and a dynamic zero step uses built-in error code 306 (InvalidLoopStep).

Floating-point ranges round each candidate to the selected binary precision before checking the endpoint. A non-finite or out-of-range candidate ends the loop without becoming the next value. If an in-range candidate rounds back to the current value while the endpoint still lies ahead, the loop fails at runtime with built-in error code 307 (RangeStepNoProgress) rather than repeating that value.

Const range loops diagnose statically known zero and no-progress steps while folding. Const templates owns those compile-time rules.

Progress records target support separately from these range semantics.

Choose the explanation level: Loop control

Loop control

Use break when a loop should end early.

Use continue when the current iteration should stop but the loop itself should keep going.

loop 0 to 10 |value|:
    if value is 2:
        continue
    ;

    if value is 7:
        break
    ;

    io.line([: [value]])
;

The loop skips 2. It ends when it reaches 7, so 7 and the later numbers are not printed.

Nested loops

break and continue affect the closest loop around them.

loop 0 to 3 |row|:
    loop 0 to 3 |column|:
        if column is 1:
            continue
        ;

        io.line([: row [row], column [column]])
    ;
;

In this example, continue skips one column. The outer row loop keeps running.

break and continue are statement-only controls for the nearest active loop.

loop 0 to 10 |value|:
    if value is 2:
        continue
    ;

    if value is 7:
        break
    ;

    io.line([: [value]])
;

break

break exits the nearest active loop immediately. Statements later in that loop body do not run for the current iteration.

continue

continue skips the rest of the nearest active loop body.

The next action depends on the loop form:

  • a conditional loop checks its condition again
  • a collection loop advances by its step to the next visited item
  • a range loop advances its counter by the step, then checks the next bound

Rules

  • break and continue are valid only inside a loop.
  • They may appear inside a branch or nested block that is itself inside a loop.
  • They target the nearest enclosing loop.
  • A break or continue that targets a loop outside a value-producing branch completes that branch without producing a value.
  • A loop nested inside the branch consumes its own break and continue, so they cannot complete the branch. The branch must still produce, exit or diverge after the loop.
  • Moth does not have labelled loop control.
  • Neither statement produces a value.
  • return and return! leave the function rather than only leaving the loop.
  • break targeting a loop does not prove divergence. A -> ! body still needs every reachable path, including that post-loop continuation, to diverge.

Template loops repeat content without break or continue. Their contract is specified by Template control flow.