Skip to content
While & For Loops
step 1/3

Reading — step 1 of 3

Loops — Repeating Execution

~2 min readControl Flow & Functions

While & For Loops

Loops allow code to execute repeatedly. We implement two loop constructs: while (the fundamental loop) and for (syntactic sugar over while).

While Loops

while (condition) body

The condition is evaluated before each iteration. If truthy, execute the body and repeat. If falsy, exit the loop.

var i = 0;
while (i < 5) {
    print i;
    i = i + 1;
}
// outputs: 0, 1, 2, 3, 4

Parsing and Executing While

whileStmt → "while" "(" expression ")" statement

Execution is straightforward:

executeWhile(stmt):
    while isTruthy(evaluate(stmt.condition)):
        execute(stmt.body)

For Loops

A for loop has three clauses: initializer, condition, and increment:

for (var i = 0; i < 10; i = i + 1) {
    print i;
}

Desugaring For to While

The elegant insight from Crafting Interpreters: a for loop is just syntactic sugar for a while loop. We desugar it during parsing:

for (init; condition; increment) body

becomes:

{
    init;
    while (condition) {
        body;
        increment;
    }
}

The outer block ensures the initializer's variable (var i) is scoped to the loop. This desugaring approach means we do not need any new AST nodes or execution logic — the existing while and block implementation handles everything.

Optional Clauses

Each for-loop clause is optional:

  • for (;;) body — infinite loop (condition defaults to true)
  • for (var i = 0; i < 10;) body — no increment
  • for (; i < 10; i = i + 1) body — no initializer

How Lua Does Loops

Lua has while, repeat...until (like do-while), and a numeric for with explicit step: for i = 1, 10, 2 do ... end. Lua's generic for with iterators is more powerful than C-style for loops. Python took a similar approach with for x in iterable.

Your Task

Implement while and for loops. Desugar for into while during parsing. Handle all optional clause combinations.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…