Back to General discussions forum
A link to lesson: "For" loop
A quote from lesson:
for
syntax allows for additional, optional value of increment. Let's set it negative e.g.:
for x = 9,1,-1 do
print(x .. ' left')
end
I should confess I often forget this -1 at the end when writing such down-counting loops - what happens then? It goes from 9 to almost infinity. On most machine types such loop will never end.
Actual behaviour:
Loop ends immediately with no iterations.
A link to playground with for
loop test: https://www.codeabbey.com/index/play/qwertyone-testforloop
Aw, what a shame :) thanks for so thorough proof-reading - I fixed the phrase (but I confess I either didn't know or completely forget this special behavior)!
I'm glad I could be of some help, Rodion.
...in many languages like C/C++ loop goes from 9 to almost infinity (e.g. execution freezes)
Rodion, asking out of curiosity, can you describe how this happens? I can't reproduce such behaviour: For loop with C/C++
I think Rodion meant he occasionally forgot to add something like i--
instead of i++
.
Because of this for (int i = 9; i > 1; i++)
would be infinite.
I suppose Lua interpreter sees that i
can't go from 9
to 1
with step being 1
and doesn't execute the loop, while C/C++
compiler just lets that happen.
Yep, exactly the case - for me it most commonly happens when I suddenly decide it is more convenient to go through array or some other data in backward direction - and modify existing loop by changing start and stop expressions, but forgetting to alter increment. In C, Java, and PHP (particularly, when creating "checkers" for problems on this site) I hit this silly mistake again and again. Of course it is a matter of personal attentiveness :)
I understood now how you run into infinite step. Thanks for explainations!
Well, it is not some Lua magic, it is just us trying to use mutually exclusive combinations of stop condition and increment value. We are just humans, after all :)
But any language which does not allow you to set stop condition separately will implement it nicely for you... examples are Pascal, Basic, Ada and almost all functional languages.