Software /
code /
prosody
Diff
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 |
line wrap: on
line diff
--- a/util/iterators.lua Mon Aug 10 15:07:32 2009 +0100 +++ b/util/iterators.lua Mon Aug 10 15:46:34 2009 +0100 @@ -90,6 +90,27 @@ end, s; end +function tail(n, f, s, var) + local results, count = {}, 0; + while true do + local ret = { f(s, var) }; + var = ret[1]; + if var == nil then break; end + results[(count%n)+1] = ret; + count = count + 1; + end + + if n > count then n = count; end + + local pos = 0; + return function () + pos = pos + 1; + if pos > n then return nil; end + return unpack(results[((count-1+pos)%n)+1]); + end + --return reverse(head(n, reverse(f, s, var))); +end + -- Convert the values returned by an iterator to an array function it2array(f, s, var) local t, var = {};