lua-users home
lua-l archive

Re: filter an array in place

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


-- 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

AltStyle によって変換されたページ (->オリジナル) /