Memoization with Closures
Cache expensive function results inside a closure-held table.
Memoization with Closures is a free Lua Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.
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.
Learn Lua with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 40
- Lessons
- 159
Frequently Asked Questions
Is the “Memoization with Closures” lesson free?
Yes — any 3 lessons of the Lua Academy learning path, including “Memoization with Closures”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
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