lua-users home
lua-l archive

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


>Just somehow I would like to get a 
>rough idea, HOW such basic changes 
>like i=i-1 or i=1 of my first thread post
>COULD get dangerous ...

Because the manual explicitly says, “Don’t do it,” which implies that the code generated by the compiler may legally choose to generate code that *doesn’t terminate the loop as you might expect* if you change the loop variable.

For example, the compiler could decide to keep two copies of the variable, one used only as a loop counter, and one used for holding the variable for use in calculations. (The loop counter might be a CPU register that isn’t used for anything else.) The compiler would even be free to optimise out any lines of code where you change the “unchangeable” variable.

Or the compiler could decide to terminate the loop by checking that the loop counter *exactly matches* the terminating condition, for example by assuming that in the loop “for n = 1,5” the value of n *will be exactly 5 at the end of the last iteration*. So if you ever set n to 6 then the loop will run forever, or at least until n wraps round past 2^63 and gets back to 5 from below.

For loops don’t have to be constrained in this way when you design a language - Go is a good example - but that is how Lua does it.

In Lua, the numeric for loop *is meant for counting in fixed steps*, and the compiler is allowed (and should be expected to) take advantage of that, at least at some times and on some processors and in some versions of the software. If you want any other kind of loop, use while instead.

The fact that “it works” is not a good reason to do it… like smoking a cigarette while filling up your car with petrol (gasoline). Most of the time, you will be fine. But once (and never more than once) you and everyone near you will not be fine at all.