[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: pairs(t, skey) and ipairs(t, skey)
- From: Leo Razoumov <slonik.az@...>
- Date: Thu, 3 Oct 2013 22:42:31 -0400
On 10/3/13, Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br> wrote:
> [..snip..]
> 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
>
I am afraid that in the code above the inner 'while' can become an infinite loop
when wrong value of 'n' is used. Below is the shorter version of the code
that does not suffer from this problem:
function npairs(t,n)
return function(x,i)
for j=i+1,n do
if x[j] then return j,x[j] end
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
--Leo--
- 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
- Re: pairs(t, skey) and ipairs(t, skey), Luiz Henrique de Figueiredo