Changeset

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
parents 1907:1dd4443e7d93
children 1916:7f8928aa0b9d
files util/array.lua
diffstat 1 files changed, 13 insertions(+), 2 deletions(-) [+]
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