Lua `next` is a function that takes two arguments: a table and a key and 
returns the another key (or nil).  Unlike an iterator, it holds no 
context.  It is guaranteed that you will iterate over all keys if you 
repeatedly call next as follows

k = next(t)
while k ~= nil do
    k = next(t, k)
end

If, however, you were to insert new items into t in the body of this loop, 
this guaranteed would no longer hold.  This is what is meant by "undefined 
behaviour", as far as I understand.

Arnaud

On Thursday, 24 December 2020 at 15:55:27 UTC Jan Mercl wrote:

> On Thu, Dec 24, 2020 at 4:08 PM Arnaud Delobelle <arn...@gmail.com> wrote:
>
> > The order is undefined but stable (provided you don't insert new 
> values), and accessible via the `next` function. Here is an example:
>
> Quoting from the provided link:
>
> """"
> next (table [, index])
>
> Allows a program to traverse all fields of a table. Its first argument
> is a table and its second argument is an index in this table. next
> returns the next index of the table and its associated value. When
> called with nil as its second argument, next returns an initial index
> and its associated value. When called with the last index, or with nil
> in an empty table, next returns nil. If the second argument is absent,
> then it is interpreted as nil. In particular, you can use next(t) to
> check whether a table is empty.
>
> The order in which the indices are enumerated is not specified, even
> for numeric indices. (To traverse a table in numerical order, use a
> numerical for.)
>
> The behavior of next is undefined if, during the traversal, you assign
> any value to a non-existent field in the table. You may however modify
> existing fields. In particular, you may clear existing fields.
> """"
>
> The word 'stable' does not seem to be present in this part of the
> specs at all, so only "The order in which the indices are enumerated
> is not specified, even for numeric indices." remains to be considered.
> That said, I see no problem with implementing it by iterating a Go
> map.
>
> Or is the Lua specification perhaps incomplete? Maybe people
> incorrectly rely on the behavior of a particular implementation.
> That's why the Go map iteration is intentionally randomized, BTW.
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/4aa8f174-2e3b-4124-9e55-44b415cce398n%40googlegroups.com.

Reply via email to