Diff

util/array.lua @ 1915:e9d5406caf8c

util.array: Fix for array:filter() (in-place filtering)
author Matthew Wild <mwild1@gmail.com>
date Mon, 05 Oct 2009 17:56:31 +0100
parent 1905:e3e0a17e0b33
child 1922:d5fe0f9b377a
line wrap: on
line diff
--- a/util/array.lua	Mon Oct 05 14:42:23 2009 +0100
+++ b/util/array.lua	Mon Oct 05 17:56:31 2009 +0100
@@ -33,11 +33,22 @@
 end
 
 function array_base.filter(outa, ina, func)
-	for k,v in ipairs(ina) do
+	local inplace, start_length = ina == outa, #ina;
+	local write = 1;
+	for read=1,start_length do
+		local v = ina[read];
 		if func(v) then
-			outa:push(v);
+			outa[write] = v;
+			write = write + 1;
 		end
 	end
+	
+	if inplace and write < start_length then
+		for i=write,start_length do
+			outa[i] = nil;
+		end
+	end
+	
 	return outa;
 end