Software /
code /
prosody
Comparison
util/array.lua @ 918:967edf874df7
util.array: New array library
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Wed, 25 Mar 2009 03:00:09 +0000 |
child | 920:e302cbc9d036 |
comparison
equal
deleted
inserted
replaced
917:f12f88b3d4a1 | 918:967edf874df7 |
---|---|
1 local array_methods = {}; | |
2 local array_mt = { __index = array_methods, __tostring = function (array) return array:concat(", "); end }; | |
3 | |
4 local function array(t) | |
5 return setmetatable(t or {}, array_mt); | |
6 end | |
7 | |
8 function array_methods:map(func, t2) | |
9 local t2 = t2 or array{}; | |
10 for k,v in ipairs(self) do | |
11 t2[k] = func(v); | |
12 end | |
13 return t2; | |
14 end | |
15 | |
16 function array_methods:filter(func, t2) | |
17 local t2 = t2 or array{}; | |
18 for k,v in ipairs(self) do | |
19 if func(v) then | |
20 t2:push(v); | |
21 end | |
22 end | |
23 return t2; | |
24 end | |
25 | |
26 | |
27 array_methods.push = table.insert; | |
28 array_methods.pop = table.remove; | |
29 array_methods.sort = table.sort; | |
30 array_methods.concat = table.concat; | |
31 array_methods.length = function (t) return #t; end | |
32 | |
33 function array_methods:random() | |
34 return self[math.random(1,#self)]; | |
35 end | |
36 | |
37 function array_methods:shuffle() | |
38 local len = #self; | |
39 for i=1,#self do | |
40 local r = math.random(i,len); | |
41 self[i], self[r] = self[r], self[i]; | |
42 end | |
43 end | |
44 | |
45 _G.array = array |