← Back to Lua Course | Chapter 5: Functions | Lesson 5 of 7

Closures

A closure is a function that remembers the local variables from where it was created.

In this page:

  1. Closures

Closures

When a function is defined inside another function it can use the outer function's local variables, called upvalues. These variables stay alive after the outer function returns, so each call to a factory creates an independent set. Closures are commonly used for counters, private state and callbacks.

Note: Each call to the outer function creates fresh upvalues, so counters made separately do not interfere.

Example: Closures

lua
local function counter()
  local n = 0
  return function()
    n = n + 1
    return n
  end
end
local c1, c2 = counter(), counter()
print(c1(), c1(), c1())
print(c2())

local fns = {}
for i = 1, 3 do fns[i] = function() return i end end
print(fns[1](), fns[2](), fns[3]())

-- Output:
-- 1	2	3
-- 1
-- 1	2	3
Common Mistakes
  1. Expecting all closures to share one counter
  2. Capturing a loop variable and expecting one shared copy
  3. Assuming local variables die when the function returns even if captured
Chapter Summary
  • Inner functions see outer locals
  • Captured variables are upvalues
  • Each factory call has its own state
  • Useful for counters and private data

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.