-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmemoize.lua
More file actions
52 lines (42 loc) · 1.12 KB
/
Copy pathmemoize.lua
File metadata and controls
52 lines (42 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
if not table.pack then
function table.pack (...)
return {n=select('#',...), ...}
end
end
if not table.unpack then
table.unpack = unpack
end
function memoize( fn )
local function fnKey( ... )
local key = ""
local args = table.pack( ... )
for i = 1, args.n do
key = key .. "[" .. tostring( args[ i ] ) .. "]"
end
return key
end
local object = {
__call = function( targetTable, ... )
local key = fnKey( ... )
local values = targetTable.__memoized[ key ]
if ( values == nil ) then
values = table.pack( fn( ... ) )
targetTable.__memoized[ key ] = values
end
if ( values.n > 0 ) then
return table.unpack( values )
end
return nil
end,
__forget = function( self ) self.__memoized = {} end,
__memoized = {},
__mode = "v",
}
return setmetatable( object, object )
end
local function fn1(...)
return ...
end
local m1 = memoize( fn1 )
local t = m1( 1, 2, 3 )
print( m1(1, 2, 3) )