lua-users home
lua-l archive

Re: Iterator question

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


Am 12.06.2013 05:21 schröbte meino.cramer@gmx.de:
Hi,
Hi!
is it possible (and how) to create an iterator with lua, which returns
the [n]th _and_ the [n+1]th value of in array/table with each call?
Sure:
 local function ip2_iter( st, var )
 var = var+1
 local v1 = st[ var ]
 if v1 ~= nil then
 return var, v1, st[ var+1 ]
 end
 end
 local function ipairs2( t )
 return ip2_iter, t, 0
 end
 for i,v,w in ipairs2( { "a", "b", "c", "d" } ) do
 print( i, v, w )
 end
1	a	b
2	b	c
3	c	d
4	d	nil
If you don't want the index, you need to create a closure to remember the current index between iterator calls ...
Thank you very much in advance for any help!
Best regards,
mcc
HTH,
Philipp

AltStyle によって変換されたページ (->オリジナル) /