Lesson on for loop - actual results does not match theory

Back to General discussions forum

qwerty     2023-12-18 11:32:48

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

Rodion (admin)     2023-12-18 11:57:33
User avatar

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)!

qwerty     2023-12-18 20:02:06

I'm glad I could be of some help, Rodion.

qwerty     2023-12-19 15:55:33

...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++

ecolog_veteran     2023-12-20 09:31:39
User avatar

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.

Rodion (admin)     2023-12-20 16:40:55
User avatar

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 :)

qwerty     2023-12-20 18:28:02

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.

Please login and solve 5 problems to be able to post at forum