[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: pairs(t, skey) and ipairs(t, skey)
- From: Dirk Laurie <dirk.laurie@...>
- Date: Tue, 1 Oct 2013 07:59:57 +0200
2013/10/1 Paul K <paulclinger@yahoo.com>:
> I was looking for a way to find if there are any keys in the hash part
> of a table without iterating the table
That is impossible in principle.
> and realized that I can use "next" to give me the answer
Using "next" amounts to iterating the table.
> as it accepts a starting key:
>
> next(t, #t) returns the first key in the hash part (if any).
No, it does not.
next(t, #t) returns the first key after #t in some undefined permutation
of the keys. There is no reason why next(t, #t) can't return a key less
than #t, even when the table has no holes.
It is similarly nowhere guaranteed that next(t,k) equals k+1 if k+1
happens to be a valid key, whether or not the table contains holes.
Moreover, it is not even guaranteed that the permutation implied by
next(t, #t) is the same every time that you use exactly the same
table constructor. Here is an example I just ran twice (Lua 5.2.2)
by simply replaying the system command:
$ lua -e "t={a='a', b='b', c='c', [3]=3, [2]=2,[1]=1} s=nil; repeat
s=next(t,s); print(t[s]) until s==nil"
a
2
1
3
b
c
nil
$ lua -e "t={a='a', b='b', c='c', [3]=3, [2]=2,[1]=1} s=nil; repeat
s=next(t,s); print(t[s]) until s==nil"
c
1
a
b
3
2
nil
$
Note in the second case, starting the iteration of the table at #t will miss
all three non-numeric keys.