lua-users home
lua-l archive

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

On Fri, Jun 4, 2021 at 11:53 AM Tom Sutcliffe <> wrote:
Hi list,

A question occurred to me just now (it is Friday afternoon after all) - the Lua manual 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". 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.



Your guess is correct -- by changing the keys in the table, you invalidate the traversal order. You may skip items, or you may see items that you'd already seen before. The latter could -- in theory -- provoke an infinite loop, if the code inside the loop repeatedly invalidates the iterator.

However, it would not be a violation of the specification if it were to instead throw an error if it detects a change to the keys during iteration. It doesn't do that, but it could.

/s/ Adam