aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--util/array.lua36
1 files changed, 27 insertions, 9 deletions
diff --git a/util/array.lua b/util/array.lua
index cf586214..cbb051d3 100644
--- a/util/array.lua
+++ b/util/array.lua
@@ -25,6 +25,15 @@ end
setmetatable(array, { __call = new_array });
+-- Read-only methods
+function array_methods:random()
+ return self[math.random(1,#self)];
+end
+
+-- These methods can be called two ways:
+-- array.method(existing_array, [params [, ...]]) -- Create new array for result
+-- existing_array:method([params, ...]) -- Transform existing array into result
+--
function array_base.map(outa, ina, func)
for k,v in ipairs(ina) do
outa[k] = func(v);
@@ -67,11 +76,7 @@ function array_base.pluck(outa, ina, key)
return outa;
end
---- These methods only mutate
-function array_methods:random()
- return self[math.random(1,#self)];
-end
-
+--- These methods only mutate the array
function array_methods:shuffle(outa, ina)
local len = #self;
for i=1,#self do
@@ -98,10 +103,23 @@ function array_methods:append(array)
return self;
end
-array_methods.push = table.insert;
-array_methods.pop = table.remove;
-array_methods.concat = table.concat;
-array_methods.length = function (t) return #t; end
+function array_methods:push(x)
+ table.insert(self, x);
+end
+
+function array_methods:pop(x)
+ local v = self[x];
+ table.remove(self, x);
+ return v;
+end
+
+function array_methods:concat(sep)
+ return table.concat(array.map(self, tostring), sep);
+end
+
+function array_methods:length()
+ return #self;
+end
--- These methods always create a new array
function array.collect(f, s, var)