Software /
code /
prosody
Comparison
util/iterators.lua @ 919:75b8afb79143
util.iterators: New iterators library
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Wed, 25 Mar 2009 03:01:10 +0000 |
child | 1522:569d58d21612 |
comparison
equal
deleted
inserted
replaced
918:967edf874df7 | 919:75b8afb79143 |
---|---|
1 --[[ Iterators ]]-- | |
2 | |
3 -- Reverse an iterator | |
4 function reverse(f, s, var) | |
5 local results = {}; | |
6 | |
7 -- First call the normal iterator | |
8 while true do | |
9 local ret = { f(s, var) }; | |
10 var = ret[1]; | |
11 if var == nil then break; end | |
12 table.insert(results, 1, ret); | |
13 end | |
14 | |
15 -- Then return our reverse one | |
16 local i,max = 0, #results; | |
17 return function (results) | |
18 if i<max then | |
19 i = i + 1; | |
20 return unpack(results[i]); | |
21 end | |
22 end, results; | |
23 end | |
24 | |
25 -- Iterate only over keys in a table | |
26 local function _keys_it(t, key) | |
27 return (next(t, key)); | |
28 end | |
29 function keys(t) | |
30 return _keys_it, t; | |
31 end | |
32 | |
33 -- Iterate only over values in a table | |
34 function values(t) | |
35 local key, val; | |
36 return function (t) | |
37 key, val = next(t, key); | |
38 return val; | |
39 end, t; | |
40 end | |
41 | |
42 -- Given an iterator, iterate only over unique items | |
43 function unique(f, s, var) | |
44 local set = {}; | |
45 | |
46 return function () | |
47 while true do | |
48 local ret = { f(s, var) }; | |
49 var = ret[1]; | |
50 if var == nil then break; end | |
51 if not set[var] then | |
52 set[var] = true; | |
53 return var; | |
54 end | |
55 end | |
56 end; | |
57 end | |
58 | |
59 --[[ Return the number of items an iterator returns ]]-- | |
60 function count(f, s, var) | |
61 local x = 0; | |
62 | |
63 while true do | |
64 local ret = { f(s, var) }; | |
65 var = ret[1]; | |
66 if var == nil then break; end | |
67 x = x + 1; | |
68 end | |
69 | |
70 return x; | |
71 end | |
72 | |
73 -- Convert the values returned by an iterator to an array | |
74 function it2array(f, s, var) | |
75 local t, var = {}; | |
76 while true do | |
77 var = f(s, var); | |
78 if var == nil then break; end | |
79 table.insert(t, var); | |
80 end | |
81 return t; | |
82 end | |
83 | |
84 -- Treat the return of an iterator as key,value pairs, | |
85 -- and build a table | |
86 function it2table(f, s, var) | |
87 local t, var = {}; | |
88 while true do | |
89 var, var2 = f(s, var); | |
90 if var == nil then break; end | |
91 t[var] = var2; | |
92 end | |
93 return t; | |
94 end |