0Pricing
Lua Academy · Lesson

Memoization with Closures

Cache expensive function results inside a closure-held table.

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
end

All lessons in this course

  1. What Are Upvalues?
  2. Shared Upvalues Between Closures
  3. Factory Functions and Generators
  4. Memoization with Closures
← Back to Lua Academy