Hans Hagen <j.ha...@xs4all.nl> writes:

> On 1/28/2020 1:10 AM, Sebastian Miele wrote:
>
> > Moreover, e.g. the example
> >
> >    for n,key in next,table.sortedkeys(mixed) do
> >       io.write(string.format("[%2i] [%2s] (t:%6s) -> ā€œ%sā€\n", n, key, 
> > type(key), mixed[key]))
> >    end
> >
> > from https://www.contextgarden.net/Table_manipulation returns different
> > results at least on different runs.
>
> you normally don't iterate over an array that way, compare:
>
> local t = { 11, "44", 22, "33" }

This is an array. No mixed keys. I do not get the point.

> for k, v in table.sortedhash(t) do
>     print(k,v,type(k),type(v))
> end
>
> local m = table.sortedkeys(t)
>
> for k, v in next, m do
>     print(k,v,type(k),type(v))
> end
>
> local m = table.sortedkeys(t)
> for k=1,#m do
>     local v = t[k]
>     print(k,v,type(k),type(v))
> end

With just integer keys they all give essentially the same and expected
result.

I tried to change t into

  local t = { [ 11 ] =  11
            , ["44"] = "44"
            , [ 22 ] =  22
            , ["33"] = "33"
            }

in case that was what you meant. But in this example numeric and
lexicographic order agree. So nothing unexpected here, too.

The only noteworthy thing is that "for k, v in next, m" indeed traverses
in order here, although, according to the Lua manual, "the order in
which the indices are enumerated is not specified, even for numeric
indices".

https://www.contextgarden.net/Table_manipulation often uses next to
iterate even over sorted results, which according to the Lua manual is
not guaranteed to yield the expected (ordered) results (in the future).
The end of the page mentions that ipairs is slower than next or numeric
for's. The text on table.prepend mentions that after prepending,
iteration via next indeed does not traverse in order any more, and a
numeric for is appropriate.

So, if https://www.contextgarden.net/Table_manipulation reflects the way
it is done in ConTeXt, it seems to be customary to partly rely on Lua's
(current) implementation details beyond Lua's specification.

But this shall be fine with me, too. Should some future implementation
of Lua change implementation details in a relevant way here, you almost
certainly will notice it first, and quickly know what to do. :-)
_______________________________________________
dev-context mailing list
dev-context@ntg.nl
https://mailman.ntg.nl/mailman/listinfo/dev-context

Reply via email to