How to Simulate for, while or do loops in Twine

UPDATE:I have written a proper <<while>> macro. The techniques below will still work but you'll probably find the new macro much easier.

Tweecode (used by Twine) does not have any notion of a loop but they can be simulated with <<if>>, <<set>> and <<display>> macros. The trick is a computer science trick called recursion where a piece of code repeatedly calls itself. So just think of passages as pieces of tweecode (functions) and the <<display>> macro as the "Call Function" command.

An example while loop

You knock at the door; <<display "WhileLoopDemo">>
The door is answered by a sleepy giant.

<<if Math.floor(Math.random()*100) lt 70>>
knock <<display "WhileLoopDemo">>

The Math.floor(Math.random()*100) code selects a random number from 0 to 99. See how the loop passage keeps on calling itself, until finally there will be a random number 70 or greater and the passage will exit back to where it left off in the start passage.
Demo, Code: .tws | .twee

An example for loop

Example for loop demo. <<set $i = 0>><<display "ForLoopDemo">>

<<if $i lte 5>>
<<print $i>>... <<set $i = $i + 1>><<display "ForLoopDemo">>

The for loop example is slightly more complex because it must setup a counting variable and increment this on every iteration of the loop.
Demo, Code: .tws | .twee

Note: The double-colon :: denotes the start of a new passage. The rest of the line following the double-colon, up to an option opening square bracket [, is the passage title. This text following the start of passage (until the passage start) is a the body of the passage.

It is possible to create custom macros that would make loops in tweecode much easier; I might even do this one day. However, if your Interactive Fiction work is relying heavily on tons of loops then it is probably time to look at implementing that functionality in JavaScript directly for efficiency reasons.

The Nicomachus includes a demonstration of a loop in a fairly simple piece of code. If you're a JavaScript wiz then you might be interested in how to create your own macros. Let me know in the comments if there are other Twine related topics you'd like covered.