slice

function slice( tab [, first [, last]] ) --> sub

Description

Returns a sub-array(slice) of an array table. slice does not affect the table itself. It is possible to use negative numbers to identifie the first and last element of the sub-array. This functions works like the lua standard function string.sub.

Parameters

tab

The array table from where we want a slice. The content of tab itself will not be changed.

first

Index where the sub-array starts in the table. As a negative index, begin indicates an offset from the end of the sequence. The value -2 means that the subarray starts with the penultimate element of the table. If first is omitted starts the sub-array from index 1.

last

Index where the sub-array ends in the table. As a negative index, begin indicates an offset from the end of the sequence. The value -2 means that the subarray ends with the penultimate element of the table. If last is omitted ends the sub-array at index #tab.

Return Values

sub

The sub-array of the assigned array table

Code

--ZFUNC-slice-v1
local function slice( tab, first, last ) --> sub
   local sub = {}
   local n = #tab

   first = first or 1
   last = last or n
   if last < 0 then
      last = n + last + 1
   elseif last > n then
      last = n
   end

   if first < 1 or first > n then
      return {}
   end

   for i = first, last do
      table.insert( sub, tab[ i ] )
   end

   return sub
end

return slice

Examples

local t = require( "taptest" )
local slice = require( "slice" )

local tab = { "a", "b", "c", "d", "e" }
t( table.concat( slice( tab, 2 ) ), "bcde" )
t( table.concat( slice( tab, 2, -2 ) ), "bcd" )
t( table.concat( slice( tab, 2, 3 ) ), "bc" )

t()

Inspired by

See also