lua-users home
lua-l archive

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


Actually in C it’s totally legal to modify the loop variable. It’s a well known source of nasty bugs if you are not careful, but the C compiler itself will not create them, the programmer does. But the Lua byte code generator could store the loop variable somewhere else than as a reference to the Lua stack, for instance directly in a reserved CPU register for performance reason and then your modification of the stack variable is simply ignored. The fact that it doesn’t currently seem to do that (under your tested conditions, but who knows if it couldn’t under other conditions?) is meaningless. The reference manual states explicitly that it’s not safe and hence you can continue to argue that it should or that it is, but the canonical reference says it’s not. That it seems to work is no guarantee that it is safe and if you do it anyways and then find a problem and try to file a bug report the answer will be: Duh, you shouldn’t do that, the manual explicitly states that it is unsafe!

If you really want to change that, you should sit down and write a paper about how to 100% safely guarantee that the Lua byte code generator never will be able to have that happen, what to lookout for when modifying that code, a comprehensive set of unit tests and then start a proposal to have that all implemented in a upcoming version of Lua. Then fight the forces of status quo ad infinitum and then it may be changed in the manuals. 😀

Rolf Kalbermatter

> On 12 Dec 2022, at 06:16, bil til <biltil52@gmail.com> wrote:
> 
> Am So., 11. Dez. 2022 um 12:33 Uhr schrieb Rolf Kalbermatter
> <rolf.kalbermatter@kalbermatter.nl>:
>> 
>> It’s not bizarre at all. Lua may be not a compiler in itself (although there exist JIT versions
>> and similar of it) but it’s written in C. And C has the notorious feature of stating many things
>> as not being defined for the sake of efficient implementations on all kind of hardware, including
>> very esoteric ones.
> 
> I have to admit, that I have not any overview how Lua does the for
> looping in detail, but I would bet that the for looping in Lua FOR
> SURE does NOT rely on any "C Compiler for looping approach". It
> typically just should be programmed very similar to the Lua while do
> end / repeat until loop, just with this additional counter variable,
> which MUST be a "normal Lua" value, so it must reside on Lua stack
> "very Lua normally".
> 
> After the comments above of Francisco, I interprete it as safe to
> interprete the warning in the reference manual more like "It is safe
> to vary the counter loop variable inside the for loop limits, but any
> new value outside the for loop might lead to undefined behaviour." ...
> I hope I will survive this and not run into explosions :).