TExcelTAD
Home › Lua › Lua Closures and Upvalues

Lua Closures and Upvalues

A closure is a function together with the local variables it uses from the scope where it was created. Those outer variables are called upvalues in Lua. They stay alive as long as the function does, even after the code that created them has returned.

lua · try it yourself
local function makeCounter()
  local count = 0              -- an upvalue of the function below
  return function()
    count = count + 1
    return count
  end
end

local nextTicket = makeCounter()
print(nextTicket())
print(nextTicket())
print(nextTicket())
1
2
3

makeCounter has finished running, yet the inner function still reads and updates count. That variable now lives only inside the closure: no other code can touch it.

Each call creates a new closure

Calling the factory again creates a fresh count. The two counters are independent:

lua · try it yourself
local function makeCounter()
  local count = 0
  return function()
    count = count + 1
    return count
  end
end

local a = makeCounter()
local b = makeCounter()
print(a(), a(), a())
print(b())
1	2	3
1

Sharing an upvalue

Several closures created in the same call share the same variable, not copies of it. This gives you private state with a small public interface:

lua · try it yourself
local function makeAccount(balance)
  local function deposit(amount)
    balance = balance + amount
  end
  local function withdraw(amount)
    if amount > balance then
      return false, "insufficient funds"
    end
    balance = balance - amount
    return true
  end
  local function getBalance()
    return balance
  end
  return { deposit = deposit, withdraw = withdraw, balance = getBalance }
end

local acct = makeAccount(100)
acct.deposit(50)
print(acct.withdraw(30))
print(acct.withdraw(500))
print(acct.balance())
print(acct.balanceValue)     -- the variable itself isn't reachable
true
false	insufficient funds
120
nil

The parameter balance is an upvalue shared by the three functions. Nobody can set it directly; they must go through deposit and withdraw.

Closures in loops

In Lua each pass of a for loop gets a new local loop variable, so closures created in a loop each capture their own value (unlike var in old JavaScript):

lua · try it yourself
local callbacks = {}
for i = 1, 3 do
  callbacks[i] = function() return "button " .. i end
end

for _, cb in ipairs(callbacks) do
  print(cb())
end
button 1
button 2
button 3

But if the closures capture a variable declared outside the loop, they all share it and see its final value:

lua · try it yourself
local callbacks = {}
local n = 0
while n < 3 do
  n = n + 1
  callbacks[n] = function() return "n is " .. n end
end
print(callbacks[1](), callbacks[3]())
n is 3	n is 3

Practical uses

Use Example
Private state counters, ID generators, the account above
Function factories makeMultiplier(3) returns a function that triples
Callbacks that remember context event handlers in games and UIs
Memoisation cache results in a table captured by the function
Iterators the generic for uses closures to keep its position
lua · try it yourself
local function makeMultiplier(factor)
  return function(x) return x * factor end
end

local double, triple = makeMultiplier(2), makeMultiplier(3)
print(double(21), triple(5))

local function memoize(fn)
  local cache = {}
  return function(n)
    if cache[n] == nil then
      cache[n] = fn(n)
      print("  computed " .. n)
    end
    return cache[n]
  end
end

local slowSquare = memoize(function(n) return n * n end)
print(slowSquare(9))
print(slowSquare(9))
42	15
  computed 9
81
81

The second slowSquare(9) call is answered from the cache, so "computed" is printed only once.

Test yourself

What is an upvalue?

  1. A global variable
  2. A local variable of an enclosing function that a closure uses
  3. A value returned by a function
  4. A metatable field

Two closures are created by the same call of a factory and both use its local x. What happens when one changes x?

  1. Nothing, each has a copy
  2. The other sees the new value: they share x
  3. An error
  4. x becomes global

In for i = 1, 3 do fns[i] = function() return i end end, what does fns[1]() return?

  1. 1
  2. 3
  3. 4
  4. nil