util.array: Expand some of the more basic methods to act more sensibly than their names suggested
authorMatthew Wild <mwild1@gmail.com>
Wed, 07 Dec 2011 05:14:58 +0000
changeset 4440 c60ed6732b34
parent 4439 1c8d2c0d02db
child 4441 a01b7207cb37
util.array: Expand some of the more basic methods to act more sensibly than their names suggested
util/array.lua
--- a/util/array.lua	Wed Dec 07 05:04:55 2011 +0000
+++ b/util/array.lua	Wed Dec 07 05:14:58 2011 +0000
@@ -25,6 +25,15 @@
 
 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 @@
 	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 @@
 	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)