From 59c937eb4308af90eb88dd4f82c328084191aff2 Mon Sep 17 00:00:00 2001 From: Matthew Wild Date: Mon, 5 Oct 2009 17:56:31 +0100 Subject: util.array: Fix for array:filter() (in-place filtering) --- util/array.lua | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) (limited to 'util') diff --git a/util/array.lua b/util/array.lua index ae3a0b5b..bbf26f32 100644 --- a/util/array.lua +++ b/util/array.lua @@ -33,11 +33,22 @@ function array_base.map(outa, ina, func) 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 -- cgit v1.2.3