2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
9 local t_insert, t_sort, t_remove, t_concat
10 = table.insert, table.sort, table.remove, table.concat;
13 local array_base = {};
14 local array_methods = {};
15 local array_mt = { __index = array_methods, __tostring = function (array) return array:concat(", "); end };
17 local function new_array(_, t)
18 return setmetatable(t or {}, array_mt);
21 function array_mt.__add(a1, a2)
22 local res = new_array();
23 return res:append(a1):append(a2);
26 setmetatable(array, { __call = new_array });
28 function array_base.map(outa, ina, func)
29 for k,v in ipairs(ina) do
35 function array_base.filter(outa, ina, func)
36 local inplace, start_length = ina == outa, #ina;
38 for read=1,start_length do
46 if inplace and write <= start_length then
47 for i=write,start_length do
55 function array_base.sort(outa, ina, ...)
63 --- These methods only mutate
64 function array_methods:random()
65 return self[math.random(1,#self)];
68 function array_methods:shuffle(outa, ina)
71 local r = math.random(i,len);
72 self[i], self[r] = self[r], self[i];
77 function array_methods:reverse()
86 function array_methods:append(array)
87 local len,len2 = #self, #array;
89 self[len+i] = array[i];
94 array_methods.push = table.insert;
95 array_methods.pop = table.remove;
96 array_methods.concat = table.concat;
97 array_methods.length = function (t) return #t; end
99 --- These methods always create a new array
100 function array.collect(f, s, var)
104 if var == nil then break; end
105 table.insert(t, var);
107 return setmetatable(t, array_mt);
112 -- Setup methods from array_base
113 for method, f in pairs(array_base) do
114 local base_method = f;
115 -- Setup global array method which makes new array
116 array[method] = function (old_a, ...)
117 local a = new_array();
118 return base_method(a, old_a, ...);
120 -- Setup per-array (mutating) method
121 array_methods[method] = function (self, ...)
122 return base_method(self, self, ...);