[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: pairs(t, skey) and ipairs(t, skey)
- From: Roberto Ierusalimschy <roberto@...>
- Date: Thu, 3 Oct 2013 10:21:13 -0300
> On 10/2/13, Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br> wrote:
> >> Another habit we should not be practicing is thinking of Lua tables as
> >> having
> >> array and hash parts.
> >
> > Exactly. This is an implementation detail for getting performance and
> > reduced
> > memory usage but Lua tables remain what they are: associative arrays.
> >
>
> Unfortunately, Lua itself encourages such a separation and provides both
> pairs and ipairs to reinforce the distinction.
pairs traverses all keys, ipairs traverses integer keys starting from
1. They have NOTHING TO DO with whether those keys live in the array
part or the hash part of a table. (How many times we will have to
repeat this?) As I have shown in a recent message, we can have the
entire sequence part of a table living in its hash part (as long as the
table was large enough when we started adding the integer keys); pairs
and ipairs still work as documented in such tables.
a = {a1 = nil, a2 = nil, a3 = nil, a4 = nil}
a[1] = 1; a[2] = 2; a[3] = 3; a[4] = 4
for i,v in ipairs(a) do print(i,v) end
print()
for i,v in pairs(a) do print(i,v) end
1 1
2 2
3 3
4 4
4 4
1 1
2 2
3 3
-- Roberto
- References:
- pairs(t, skey) and ipairs(t, skey), Andrew Starks
- Re: pairs(t, skey) and ipairs(t, skey), Luiz Henrique de Figueiredo
- Re: pairs(t, skey) and ipairs(t, skey), Tom N Harris
- Re: pairs(t, skey) and ipairs(t, skey), Luiz Henrique de Figueiredo
- Re: pairs(t, skey) and ipairs(t, skey), Leo Razoumov