fnil

function fnil( f, ... ) --> mf

Description

Takes a function f and returns a function that calls f and replacing nil arguments to f with the supplied values . Note that the function f can take any number of arguments, not just the one(s) being nil-patched.

Parameters

f

Function that should have default values for their parameters.

Default values for the parameters.

Return Values

mf

Wrapper function that defines default values for f.

Code

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

   local defaults = { ... }

   return function ( ... )
      local args = { ... }
      local merged = {}

      for i, v in ipairs( defaults ) do
         local arg = args[ i ]
         if arg ~= nil then
            table.insert( merged, arg )
         else
            table.insert( merged, v )
         end
      end

      return f( unwrap( merged ) )
   end
end

return fnil

Examples

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

local function favs( age, food )
   return string.format( "I'm %d years old and eat %s.", age, food )
end

local favs_with_defaults = fnil( favs, 28, "waffles" )

t.is( "I'm 64 years old and eat cranberries.",
      favs_with_defaults( 64, "cranberries" ) )

t.is( "I'm 28 years old and eat anchovy pizza.",
      favs_with_defaults( nil, "anchovy pizza" ) )

t.is( "I'm 16 years old and eat waffles.",
      favs_with_defaults( 16 ) )

t.is( "I'm 28 years old and eat waffles.",
      favs_with_defaults() )

t.done()

Inspired by