lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


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--