Lua Intermediate: OOP, Closures & Patterns

Lesson 1 of 5

Closures and Upvalues

Lua functions can reference variables from an enclosing scope even after that scope has returned, this is a closure. The captured variable is called an upvalue.

A closure example

Lua

Each call to makeCounter creates a fresh count variable, the inner function closes over that specific instance, not a shared global. counter1 and counter2 don't interfere with each other.

Why this matters

Closures are how you build private state without a class: count isn't reachable from outside the returned function, there's no way to read or reset it except by calling counter1() again. This pattern shows up constantly, for example a memoized/cached computation.

Lua

NOTE

An upvalue is shared by reference, not copied. If two closures created in the same call to makeCounter both capture the same count, calling one will affect what the other sees. Each separate call to makeCounter, though, creates a brand-new count.

📝 Closures Quiz

Passing score: 70%
  1. 1.What is the name for a variable an inner function captures from its enclosing scope?

  2. 2.Two separate calls to the same closure-returning function share the exact same captured variable.

  3. 3.A function that captures variables from its enclosing scope is called a ____.