splice

function splice( tab, idx [, n [, ...]] ) --> removed

Description

Changes the content of an array table, adding new elements while removing old elements. It is possible to use negative numbers to identifie the first and last element of the sub-array.

Parameters

tab

The array tables where you want to remove or replace elements

idx

Index at which to start changing the array table. If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end.

n

An integer indicating the number of old elements to remove. If n is 0, no elements are removed. In this case, you should specify at least one new element(). If n is greater than the number of elements left in the array starting at index, then all of the elements through the end of the array will be deleted. If no n parameter is specified, all elements after index are removed.

The elements to add to the array. If no elements are specified, splice simply removes elements from the array table.

Return Values

removed

An array table containing the removed elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

Code

--ZFUNC-splice-v1
local function splice( tab, idx, n, ... ) --> removed
   local values = { ... }
   local init_tab_size = #tab

   local removed = {}
   if n > 0 then
      for i = idx, ( idx + n - 1 ) do
         table.insert( removed, tab[ i ] )
         tab[ i ] = nil
      end
   end

   local tail = {}
   for i = ( idx + n ), init_tab_size do
      table.insert( tail, tab[ i ] )
      tab[ i ] = nil
   end

   local i = idx
   for _, v in ipairs( values ) do
      tab[ i ] = v
      i = i + 1
   end

   i = idx + #values
   for _, v in ipairs( tail ) do
      tab[ i ] = v
      i = i + 1
   end

   return removed
end

return splice

Examples

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

-- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
-- should work like the JavaScript Array.prototype.splice function"

local fishlist = { "angel", "clown", "mandarin", "surgeon" }

local removed = splice( fishlist, 3, 0, "drum" )
t.same( { "angel", "clown", "drum", "mandarin", "surgeon" }, fishlist )
t.same( {}, removed )

removed = splice( fishlist, 4, 1 )
t.same( { "angel", "clown", "drum", "surgeon" }, fishlist )
t.same( { "mandarin" }, removed )

removed = splice( fishlist, 3, 1, "trumpet" )
t.same( { "angel", "clown", "trumpet", "surgeon" }, fishlist )
t.same( { "drum" }, removed )

removed = splice( fishlist, 1, 2, "parrot", "anemone", "blue" )
t.same( { "parrot", "anemone", "blue", "trumpet", "surgeon" }, fishlist )
t.same( { "angel", "clown" }, removed )

removed = splice( fishlist, 4, 8000 )
t.same( { "parrot", "anemone", "blue" }, fishlist )
t.same( { "trumpet", "surgeon" }, removed )

t.done()

Inspired by