lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Jun 11, 2013, at 9:23 PM, Petite Abeille <petite.abeille@gmail.com> wrote:

> I'm looking for a little memoize function [1] that supports multiple arguments and multiple return values, including nils.

FWIW, a slightly streamlined version:

local function Key( ... )
  local aBuffer = { select( '#', ... ) }

  for anIndex = 1, aBuffer[ 1 ] do
    aBuffer[ #aBuffer + 1 ] = tostring( select( anIndex, ... ) ):gsub( '%|', '%1%1' )
  end

  return table.concat( aBuffer, '|' )
end

local function Memoize( aFunction )
  local aCache = {}

  assert( aFunction, ( 'bad argument #1 to %q (callable expected, got %s)' ):format( debug.getinfo( 1, 'n' ).name, type( aFunction ) ) )

  return function( ... )
    local aKey = Key( ... )
    local aValue = aCache[ aKey ] or table.pack( aFunction( ... ) )

    aCache[ aKey ] = aValue

    return table.unpack( aValue, 1, aValue.n )
  end
end