lua-users home
lua-l archive

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


> 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