Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Going round again

FOR

FOR steps through whatever you give it. Give it a range and it counts.

FOR i = 1 ... 3
    PRINT "lap", i
END FOR
lap 1
lap 2
lap 3

A range goes whichever way gets it from its start to its end, so counting down needs nothing special. To take bigger steps, add !! step(n).

That !! is the WOMT operator: Wait! One more thing! It’s for when a statement was all finished and then you remembered something else it needed. What comes after it is a modifier — an extra, named setting on a keyword. You’ll be making your own later.

FOR i = 3 ... 1
    PRINT i
END FOR
PRINT "lift off!"

FOR i = 0 ... 20 !! step(5)
    PRINT "tick", i
END FOR
3
2
1
lift off!
tick 0
tick 5
tick 10
tick 15
tick 20

Give FOR a list and it hands you each item. Ask for two names and you get the position as well. A map gives its keys and values.

FOR fruit = ["apple", "pear"]
    PRINT fruit
END FOR

FOR place, fruit = ["apple", "pear"]
    PRINT place, fruit
END FOR

FOR name, hp = {ada: 10, grace: 30}
    PRINT name, "has", hp
END FOR
apple
pear
0 apple
1 pear
ada has 10
grace has 30

NEXT closes a FOR just as END FOR does. Use whichever you like.

FOR i = 1 TO 3
    PRINT i
NEXT i
1
2
3

From BASIC: FOR i = 1 TO 10 ... NEXT i works as written. STEP is the modifier !! step(2).

From Python: FOR item = list is your for item in list, and the two-name form is your enumerate.

From JavaScript: One FOR does the work of for, for...of and for...in.

From Lua: No pairs or ipairs: hand FOR the list or the map itself. And positions start at 0 here.

WHILE and DO

WHILE tests before each pass. DO runs first and can test afterwards, with LOOP WHILE or LOOP UNTIL.

fuel = 3
WHILE fuel > 0
    PRINT "burning", fuel
    fuel = fuel - 1
END WHILE

DO
    fuel = fuel + 2
LOOP UNTIL fuel >= 5
PRINT "refuelled to", fuel
burning 3
burning 2
burning 1
refuelled to 6

WEND closes a WHILE too, and DO WHILE and DO UNTIL put the test at the top, if that’s how your fingers remember it.

BREAK and CONTINUE

BREAK leaves the loop. CONTINUE skips to its next pass.

FOR n = 1 ... 10
    IF n MOD 2 = 0 THEN CONTINUE
    IF n > 7 THEN BREAK
    PRINT n
END FOR
1
3
5
7

Crash-tan’s Tip: Try writing a loop that never ends over there, like WHILE TRUE with nothing to stop it. I’ll let it run for a bit and then step in, so you can’t get stuck.