Changeset

5857:8613888d0f9e

util.array: Improve array:reverse() and make it work as both method and non-mutating function
author Kim Alvefur <zash@zash.se>
date Sun, 06 Oct 2013 23:18:54 +0200
parents 5856:e3e593eb81d1
children 5858:89b16a160cbc 5859:e327f2d4e09f
files util/array.lua
diffstat 1 files changed, 20 insertions(+), 9 deletions(-) [+]
line wrap: on
line diff
--- a/util/array.lua	Sun Oct 06 23:17:05 2013 +0200
+++ b/util/array.lua	Sun Oct 06 23:18:54 2013 +0200
@@ -11,6 +11,7 @@
 
 local setmetatable = setmetatable;
 local math_random = math.random;
+local math_floor = math.floor;
 local pairs, ipairs = pairs, ipairs;
 local tostring = tostring;
 
@@ -84,6 +85,25 @@
 	return outa;
 end
 
+function array_base.reverse(outa, ina)
+	local len = #ina;
+	if ina == outa then
+		local middle = math_floor(len/2);
+		len = len + 1;
+		local o; -- opposite
+		for i = 1, middle do
+			o = len - i;
+			outa[i], outa[o] = outa[o], outa[i];
+		end
+	else
+		local off = len + 1;
+		for i = 1, len do
+			outa[i] = ina[off - i];
+		end
+	end
+	return outa;
+end
+
 --- These methods only mutate the array
 function array_methods:shuffle(outa, ina)
 	local len = #self;
@@ -94,15 +114,6 @@
 	return self;
 end
 
-function array_methods:reverse()
-	local len = #self-1;
-	for i=len,1,-1 do
-		self:push(self[i]);
-		self:pop(i);
-	end
-	return self;
-end
-
 function array_methods:append(array)
 	local len,len2  = #self, #array;
 	for i=1,len2 do