[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: RE: for vs while
- From: John Mckenna <jmckenna@...>
- Date: Sat, 16 Feb 2002 13:45:55 -0000
mlkesl <firstname.lastname@example.org> writes:
>I can understand it autoincrementing the index,
>but that doesn't exactly mean changing the index
>in the for loop is erroneous...just odd... right?
"The behavious is undefined if you assign to the index inside the block"
Have you had previous contamination from C? It sounds like you want
for loops to behave as they do in there - as thinly disguised whiles.
A for loop simply says "do this bit of code this many times". As a
convenience, it lets you read to the index. The whole point of a for
loop is that the number of iterations is known before the loop is
entered. This is a very useful property. It makes it much easier to
check that your program is correct (or at least, that bit won't do
anything obviously stupid).
Now, according to the rules, the behaviour of your example
return input + 1
for i=1,10000000 do
i = F(i)
is undefined. But I was curious to see what it would do. It turns
out that i is incremented twice each loop, and so the for loop only
runs half as many iterations as your while loop. I think that goes
a long way towards explaining the difference in speed you observed.
It's still wrong. Don't assign to the index. It won't necessarily
do the same thing on different versions of Lua.
-Virus scanned and cleared ok