LUA / CHAPTER 09

Closures and module boundaries

Advanced

Preserve private working state through lexical scope.

By the end of this chapter

  • Explain captured local variables
  • Create independent function factories
  • Return a focused module interface

The idea

A function can retain access to local variables from the scope where it was created. Such a function is a closure, and the retained variables are often called upvalues. This lets a factory return behavior that remembers private state between calls. Each execution of the factory creates its own local state, so separate factory calls can create independent counters or validators.

A module commonly returns a table containing the functions it wants callers to use. Helper functions and captured variables can remain local rather than becoming global names. A closure is not automatically pure: if it updates an upvalue, later calls can observe the change. Document that behavior, and avoid sharing one closure instance between callers that are supposed to have independent state.

Lua example
local function counter(start)
  local n = start
  return function() n = n + 1; return n end
end
local a = counter(0)
local b = counter(10)
print(a())
print(a())
print(b())
Result
1
2
11

The two returned functions capture different n variables. Repeated calls to a update its own retained value without changing the state captured by b.

Try it yourself

Create a factory returning a function that accumulates supplied amounts and returns the running total.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does this print?
local n = 2
local function nextValue() n = n + 3; return n end
print(nextValue())
print(nextValue())