[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: filter an array in place
- From: Mark Hamburg <mark@...>
- Date: Sat, 15 Jan 2011 10:59:27 -0800
-- Remove items from arr for which fn returns false.
-- If fn throws an exception, the array will get messed up.
function filter_array( arr, fn )
local n = #arr
local j = 0 -- insert location
-- make a pass over the array sliding down the values
-- that pass the test
for i = 1, n do
local v = arr[ i ]
if fn( v ) then
j = j + 1
if j ~= i then
arr[ j ] = v
end
end
end
-- clear any trailing entries
for i = j + 1, n do
arr[ i ] = nil
end
end