[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: memoize?
- From: Petite Abeille <petite.abeille@...>
- Date: Tue, 11 Jun 2013 23:34:46 +0200
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