constantly

function constantly( ... ) --> func

Description

Returns a function that returns allways as result.

Parameters

A variable number of values that should be the return values of the function.

Return Values

func

A function that returns the defined values.

Code

--ZFUNC-constantly-v1
local function constantly( ... ) --> func
   --ZFUNC-unwrap-v1
   local function unwrap( tab, i, j )
      local unpack = unpack or table.unpack
      return unpack( tab, i, j )
   end

   local res = { ... }
   return function ( ... )
      return unwrap( res )
   end
end

return constantly

Examples

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

f = constantly( "the usual suspect" )

t( f( 123 ), "the usual suspect" )
t( f( "sdfsadg" ), "the usual suspect" )

f = constantly( 42, true, "cow" )

t( same( { f( 123 ) }, { 42, true, "cow" } ), true )
t( same( { f( 1, 2, 3 ) }, { 42, true, "cow" } ), true )

t()

Inspired By

See also