Lua provides full lexical scoping. An inner function has direct access to local variables declared in any enclosing outer function. These captured variables are known as Upvalues.
Anatomy of an Upvalue
An upvalue is not a copy of a value; it is a reference to the actual storage location of the variable.
local function createAccount(initialBalance)
-- 'balance' is local to createAccount, but captured by the returned closures!
local balance = initialBalance
local account = {}
function account.deposit(amount)
balance = balance + amount
return balance
end
function account.withdraw(amount)
if amount > balance then
error("Insufficient funds")
end
balance = balance - amount
return balance
end
function account.getBalance()
return balance
end
return account
end
local myBank = createAccount(500)
myBank.deposit(200)
print("Balance: " .. myBank.getBalance()) -- 700
-- 'balance' cannot be accessed or modified directly from outside! Pure private state!
Higher-Order Functional Utilities
Because functions are first-class values, standard functional programming paradigms (Map, Filter, Reduce) are straightforward to implement:
-- Functional Map
local function map(list, transformFn)
local result = {}
for i, item in ipairs(list) do
result[i] = transformFn(item)
end
return result
end
-- Functional Filter
local function filter(list, predicateFn)
local result = {}
for _, item in ipairs(list) do
if predicateFn(item) then
result[#result + 1] = item
end
end
return result
end
-- Usage
local numbers = {1, 2, 3, 4, 5, 6}
local evens = filter(numbers, function(n) return n % 2 == 0 end)
local doubled = map(evens, function(n) return n * 2 end)
-- doubled is {4, 8, 12}
Function Memoization Decorator
Closures allow wrapping functions to cache expensive calculations:
local function memoize(fn)
local cache = {}
return function(arg)
if cache[arg] == nil then
cache[arg] = fn(arg)
end
return cache[arg]
end
end
local expensiveFibonacci
expensiveFibonacci = memoize(function(n)
if n <= 1 then return n end
return expensiveFibonacci(n - 1) + expensiveFibonacci(n - 2)
end)
print(expensiveFibonacci(40)) -- Computes instantly via memoized cache!
Exercises
- Write a function
compose(f, g)that returns a closure evaluatingf(g(x)). - Implement a rate-limiter closure that allows a function to be executed at most once every $N$ seconds.
- Explain the memory lifecycle of an upvalue when the enclosing function terminates.