lua-users home
lua-l archive

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


On 04/06/2021 18:53, Tom Sutcliffe wrote:
Hi list,

A question occurred to me just now (it is Friday afternoon after all)
- the Lua manual https://www.lua.org/manual/5.4/manual.html#pdf-next
states that

"The behavior of next is undefined if, during the traversal, you
assign any value to a non-existent field in the table"

Which I understand the general meaning of, but the manual's wording
got me wondering. Normally "undefined behavior" in the context of a
programming language means "your code may do absolutely anything
including crash or evolve into Skynet".

The meaning you cite is so defined (no pun intended), AFAIK, only in C and C++ standards, which go a long way to specify what they intend with "undefined behavior".

For the other languages I know, I don't remember having seen such a precise definition of that term (please someone chime in, if I'm wrong). They usually blur the distinction of terms like "unspecified" and "undefined", for example (something C/C++ do not).

Since Lua has no formal standard that defines the exact meaning of "undefined" (no pun intended), it would be reasonable to infer that "undefined" has no precise meaning. OTOH, PUC Lua implemantation relies heavily on C, so it is very reasonable to suspect (without further confirmation from authors) that the promised undefined behavior might be "C undefined behavior", i.e. the worst possible (i.e. nasal demons!).

Bottom line: good question!


With Lua however I've always
understood that (unless you use the debug library, or other native
calls into 3rd party libraries) it should never be possible to write
Lua source which compiles but crashes the interpreter, or otherwise
trashes the native interpreter state. I'm ignoring invalid bytecode
here, as that's understood to offer no guarantees. And of course
there have been a handful of bugs over the years that let you do
that, but those were clearly bugs and got fixed.

As far as I can see, this is the only place in the manual that uses
the phrase "undefined behaviour", so there isn't anything else to
compare it to.

So, what exactly are the guarantees on what `next` might do if you
violate the assignment constraint? "Not correctly let you traverse
the entire table" is a given, but what else? Get stuck in a loop
hanging the interpreter? Throw an "invalid key to next" error?
Actually crash? My guess would be "not correctly traverse", based on
my rough understanding of how table traversal works, but I'd be
interested to know what the intended behavior is, and of course if
anyone happens to know how any particular Lua version actually
behaves.


As I stated, good question. This should be addressed in the manual, at least to change the word "undefined" with a more explicit sentence, IMO.


Cheers,

Tom


Cheers,

-- Lorenzo