Memoization with Closures
Cache expensive function results inside a closure-held table.
Memoization with Closures is a free Lua Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is Memoization?
Memoization caches the results of expensive function calls so that repeated calls with the same arguments return the cached result instantly.
Basic Memoize Wrapper
A closure holds a cache table. On first call, compute and store. On repeat calls, return the stored value.
local function memoize(fn)
local cache = {}
return function(x)
if cache[x] == nil then
cache[x] = fn(x)
end
return cache[x]
end
endMemoized Fibonacci
Memoizing the recursive Fibonacci function reduces its time complexity from exponential to linear.
local fib
fib = memoize(function(n)
if n <= 1 then return n end
return fib(n-1) + fib(n-2)
end)
print(fib(30)) -- 832040 (fast!)Multi-Argument Memoization
For functions with multiple arguments, compose a cache key string from all arguments.
local function memoize2(fn)
local cache = {}
return function(a, b)
local key = a .. "," .. b
if cache[key] == nil then cache[key] = fn(a, b) end
return cache[key]
end
endNested Cache Tables
For mixed argument types, use nested tables keyed by each argument for O(1) lookup without string serialization.
local function nestedMemo(fn)
local cache = {}
return function(a, b)
cache[a] = cache[a] or {}
if cache[a][b] == nil then cache[a][b] = fn(a, b) end
return cache[a][b]
end
endCache Invalidation
Memoization assumes pure functions (no side effects, same output for same input). Functions with side effects should not be memoized without careful cache invalidation.
TTL-Based Memoization
Add time-to-live logic using os.time() to expire cached entries.
local function memoizeTTL(fn, ttl)
local cache = {}
return function(x)
local entry = cache[x]
if entry and os.time() - entry.time < ttl then
return entry.value
end
cache[x] = {value = fn(x), time = os.time()}
return cache[x].value
end
endWeak Value Cache
Use weak values so cached results can be garbage collected when memory is tight.
local function memoizeWeak(fn)
local cache = setmetatable({}, {__mode = "v"})
return function(x)
if cache[x] == nil then cache[x] = fn(x) end
return cache[x]
end
endRecursive Memoization Pattern
For mutually recursive functions, assign the memoized wrapper before the recursive body uses it, so recursion hits the cache.
Bounded Cache (LRU sketch)
For memory control, implement an LRU cache that evicts the least-recently-used entry when the cache exceeds a maximum size.
Memoization in Practice
Common uses: expensive mathematical computations, database query result caching, Lua pattern compilations, and config file parsing.
Memoization Question
Why should memoization only be applied to pure functions?
Recap: Memoization
Memoization uses a closure-held cache to store results by argument key, eliminating redundant computations. Use weak tables for memory safety and add TTL for time-sensitive caches.
Frequently asked questions
Is the “Memoization with Closures” lesson free?
Yes — the full text of “Memoization with Closures” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.
What will I learn in “Memoization with Closures”?
Cache expensive function results inside a closure-held table. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Lua Academy?
No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Memoization with Closures” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Lua Academy lesson?
Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- What Are Upvalues?
- Shared Upvalues Between Closures
- Factory Functions and Generators
- Memoization with Closures