示例工程 13-closures-and-upvalues
13-closures-and-upvalues/03-memoize/main.lua
-- @runtimes lua54 luajit
--- 演示:用闭包缓存实现记忆化。
local M = {}
local function memoize(fn)
local cache = {}
return function(value)
local cached = cache[value]
if cached == nil then
cached = fn(value)
cache[value] = cached
end
return cached
end
end
--- @return table { first = integer, second = integer, calls = integer }
function M.run(log)
log = log or print
local calls = 0
local slow_square = memoize(function(value)
calls = calls + 1
return value * value
end)
local first = slow_square(4)
local second = slow_square(4)
log(("first=%d second=%d calls=%d"):format(first, second, calls))
return { first = first, second = second, calls = calls }
end
if not ... then
M.run()
end
return M