removeif

function removeif( arr, fv, init ) --> removed

Description

Looks through an array table and removes each element that matches the truth function. The function returns all removed elements.

Parameters

arr

The array table where you want to remove elements.

fv

Check function that checks the values.

init

Specifies where to start the removing of elements, the default value is 1.

Return Values

removed

An array table with all removed elements.

Code

--ZFUNC-removeif-v1
local function removeif( arr, fv, init ) --> removed
   init = init or 1
   local removed = {}
   local i = 1
   while i <= #arr do
      if fv( arr[ i ] ) then
         local r = table.remove( arr, i )
         table.insert( removed, r )
      else
         i = i+1
      end
   end
   return removed
end

return removeif

Examples

local t = require( "tapered" )
local removeif = require( "removeif" )

local iseven = require( "iseven" )

arr = { 1, 2, 3, 4, 5, 6, 7 }
removed = removeif( arr, iseven )
t.same( { 1, 3, 5, 7 }, arr )
t.same( { 2, 4, 6 }, removed )

t.done()

Inspired by

See also