removerange

function removerange( arr, first [, last] ) --> removed

Description

Removes from arr the elements between the positions first and last, shifting down the following elements to close the space, if necessary. The removed elements will be returned inside an array table.

Parameters

arr

The array table where you want to remove elements.

first

The position of the first element that should be removed.

last

The position of the last element that should be removed., the default value is #arr.

Return Values

removed

An array table with all removed elements.

Code

--ZFUNC-removerange-v1
local function removerange( arr, first, last ) --> removed
   last = last or #arr
   local removed = {}
   local i = 1
   while i <= last do
      if i >= first and i <= last then
         local r = table.remove( arr, i - #removed )
         table.insert( removed, r )
      end
      i = i+1
   end
   return removed
end

return removerange

Examples

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

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

removed = removerange( arr, 2, 4 )
t.same( { 1, 5 }, arr )
t.same( { 2, 3, 4 }, removed )

t.done()

See also