Comparison

util/iterators.lua @ 1660:ae2f60a20428

util.iterators: Add tail() iterator, to return the last n items
author Matthew Wild <mwild1@gmail.com>
date Mon, 10 Aug 2009 15:46:34 +0100
parent 1659:6092fc9b078b
child 2923:b7049746bd29
comparison
equal deleted inserted replaced
1659:6092fc9b078b 1660:ae2f60a20428
88 c = c + 1; 88 c = c + 1;
89 return f(s, var); 89 return f(s, var);
90 end, s; 90 end, s;
91 end 91 end
92 92
93 function tail(n, f, s, var)
94 local results, count = {}, 0;
95 while true do
96 local ret = { f(s, var) };
97 var = ret[1];
98 if var == nil then break; end
99 results[(count%n)+1] = ret;
100 count = count + 1;
101 end
102
103 if n > count then n = count; end
104
105 local pos = 0;
106 return function ()
107 pos = pos + 1;
108 if pos > n then return nil; end
109 return unpack(results[((count-1+pos)%n)+1]);
110 end
111 --return reverse(head(n, reverse(f, s, var)));
112 end
113
93 -- Convert the values returned by an iterator to an array 114 -- Convert the values returned by an iterator to an array
94 function it2array(f, s, var) 115 function it2array(f, s, var)
95 local t, var = {}; 116 local t, var = {};
96 while true do 117 while true do
97 var = f(s, var); 118 var = f(s, var);