numseq

function numseq( n [, init [, f]] ) --> seq

Description

Returns a sequence of numbers.

Parameters

n

Defines the number of values that should be generated.

init

Optional start value of the sequence, the default is 0.

f

Optional function to generate the values for the sequence. It gets the last value as input and must return a new one. The default function increments the last value with 1.

Return Values

seq

Array table with the generated sequence of numbers.

Code

--ZFUNC-numseq-v1
local function numseq( n, init, f ) --> seq
   init = init or 0
   f = f or function ( v )
      return v + 1
   end

   local result = {}
   table.insert( result, init )
   for i = 2,n do
      table.insert( result, f( result[ i - 1 ] ) )
   end

   return result
end

return numseq

Examples

local t = require( "taptest" )
local numseq = require( "numseq" )
local same = require( "same" )


seq = numseq( 10 )
t( same( seq, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } ), true )

seq = numseq( 5, 1 )
t( same( seq, { 1, 2, 3, 4, 5 } ), true )

seq = numseq( 5, 1, function ( v ) return v * 2 end )
t( same( seq, { 1, 2, 4, 8, 16 } ), true )

t()