lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Thanks for the explanation.

Now I see the difference between for and while
is not that great, about 7s vs 6s with that loop.

I still don't quite see exactly why it would be so
'wrong' to allow the for loop to work with a local
variable for the index instead of its own, but oh well.

I think many users could be confused by this, as they
may also have been 'contaminated' by C. :p

I guess the solution is to not use/support for loops.
I haven't got too far into lua, but I hope there are
not other loops/blocks in lua that act this way, creating
their own little scope to run in... *wince*

--- In lua-l@y..., John Mckenna <jmckenna@r...> wrote:
> mlkesl <kaishaku13@h...> 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
> 
>   function F(input)
>     return input + 1
>   end
>   
>   for i=1,10000000 do
>     i = F(i)
>   end
> 
> 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