once

function once( f ) --> mfunc

Description

Creates a version of the function that can only be called one time. Additional calls of the modified function will have no effect, returning the value from the original call.

Parameters

f

The function that should be wrapped.

Return Values

mfunc

The modified version of the function that can be used just one time.

Code

--ZFUNC-once-v1
local function once( f ) --> mfunc
   local executed = false
   local mfunc = nil

   return function ( ... )
      if not executed then
         mfunc = f( ... )
         executed = true
      end
      return mfunc
   end
end

return once

Example

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

local v = 3

local add = function( n )
   v = v + n
   return v
end

local f = once( add )
t.is( 8, f( 5 ) )
t.is( 8, f( 10 ) )

t.done()

Inspired By