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( "taptest" )
local once = require( "once" )

local v = 3

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

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

t()

Inspired By