Comparison

util/array.lua @ 920:e302cbc9d036

util.array: Expose array.* functions, to be used for unwrapped arrays
author Matthew Wild <mwild1@gmail.com>
date Thu, 26 Mar 2009 03:55:45 +0000
parent 918:967edf874df7
child 922:0e45234360cd
comparison
equal deleted inserted replaced
919:75b8afb79143 920:e302cbc9d036
1 local array_methods = {}; 1 local array = {};
2 local array_mt = { __index = array_methods, __tostring = function (array) return array:concat(", "); end };
3 2
4 local function array(t) 3 local array_mt = { __index = array, __tostring = function (array) return array:concat(", "); end };
4 local function new_array(_, t)
5 return setmetatable(t or {}, array_mt); 5 return setmetatable(t or {}, array_mt);
6 end 6 end
7 7
8 function array_methods:map(func, t2) 8 setmetatable(array, { __call = new_array });
9
10 function array:map(func, t2)
9 local t2 = t2 or array{}; 11 local t2 = t2 or array{};
10 for k,v in ipairs(self) do 12 for k,v in ipairs(self) do
11 t2[k] = func(v); 13 t2[k] = func(v);
12 end 14 end
13 return t2; 15 return t2;
14 end 16 end
15 17
16 function array_methods:filter(func, t2) 18 function array:filter(func, t2)
17 local t2 = t2 or array{}; 19 local t2 = t2 or array{};
18 for k,v in ipairs(self) do 20 for k,v in ipairs(self) do
19 if func(v) then 21 if func(v) then
20 t2:push(v); 22 t2:push(v);
21 end 23 end
22 end 24 end
23 return t2; 25 return t2;
24 end 26 end
25 27
26 28
27 array_methods.push = table.insert; 29 array.push = table.insert;
28 array_methods.pop = table.remove; 30 array.pop = table.remove;
29 array_methods.sort = table.sort; 31 array.sort = table.sort;
30 array_methods.concat = table.concat; 32 array.concat = table.concat;
31 array_methods.length = function (t) return #t; end 33 array.length = function (t) return #t; end
32 34
33 function array_methods:random() 35 function array:random()
34 return self[math.random(1,#self)]; 36 return self[math.random(1,#self)];
35 end 37 end
36 38
37 function array_methods:shuffle() 39 function array:shuffle()
38 local len = #self; 40 local len = #self;
39 for i=1,#self do 41 for i=1,#self do
40 local r = math.random(i,len); 42 local r = math.random(i,len);
41 self[i], self[r] = self[r], self[i]; 43 self[i], self[r] = self[r], self[i];
42 end 44 end