[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: pairs(t, skey) and ipairs(t, skey)
- From: Luiz Henrique de Figueiredo <lhf@...>
- Date: Thu, 3 Oct 2013 23:15:09 -0300
> Lua table distinguishes sequential keys (from 1 through N) that can be
> iterated in order using ipairs from the other keys iterated via pairs
> that visit all the keys in a non-specified order.
No, Lua makes no such distinction. ipairs does because it provides a view
of the table as a sequence.
> Another related question: How can I iterate sequential part of a table
> from 1 through N visiting only even (or odd) elements?
The crucial point in knowing N. Here is a variant of ipairs that skips
nil entries. But it needs N.
function npairs(t,n)
return function(x,i)
i=i+1
if i>n then
return nil
else
while x[i]==nil do i=i+1 end
return i,x[i]
end
end,t,0
end
a={}
n=20
for i=1,n do if i%3~=0 then a[i]=i end end
for k,v in npairs(a,n) do print(k,v) end
- 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
- Re: pairs(t, skey) and ipairs(t, skey), Roberto Ierusalimschy
- Re: pairs(t, skey) and ipairs(t, skey), Leo Razoumov