Twine 2. Sugarcube 2.34.1
<<for _i to 0; _i lt 10; _i = _i+1>>
I set the counter to 0, then change it to 1, and then print it.
But it prints 0 rather than 1.
On the final pass, the counter equals 9 when tested, then it is incremented to 10 and printed, and yet the last number printed is 9. Again, I don’t see why that is.
I’m wondering why this is. Does the code not execute in the order humans read it?
The post expression is executed after the 3-part loop iteration, not before.
<<for INIT ; CONDITIONAL ; POST>>
INIT is executed once. Generally, to initialize any loop variables.
CONDITIONAL is checked. If it yields truthy, then go to step 3, else stop the loop.
LOOP CONTENTS are executed.
POST is executed.
- Repeat step 2.
<<for>> macro for additional details.
Right, this is based on some programming language traditions that were more about what was convenient for the computer rather than what was convenient to the programmer.
So it starts with the first statement (initialize
_i to 0).
Then each time through the loop it checks the second statement (
_i lt 10) to see if it should do the loop thing (if true) or exit the loop (if false).
Then at the end of the loop it does the third thing (
_i = _i + 1) and then goes back to the top to check the condition again.
_i is 9, then you print it, you increment it to 10, and then it goes back to the top and checks. Now it’s no longer less than 10, so it skips the loop body and doesn’t print 10.
Hope that helps…
Thanks. That clears that up for me.
I could make my loop print 1 thru 10 by tinkering with it, but I wanted to understand the why of it. You explained it clearly.