Closures: Functions That Remember

You can create a function inside another function, and even return it. The inner function can use the local variables of the outer function. It keeps that access even after the outer function has finished. A function that keeps access to outside local variables like this is called a closure.

The classic example is a counter:

function makeCounter()
    local count = 0
    return function()
        count = count + 1
        return count
    end
end

local counter = makeCounter()
print(counter())
print(counter())
print(counter())

Output:

1
2
3

Step by step:

  1. makeCounter() creates a local variable count with the value 0.
  2. It returns an anonymous function, and makeCounter is done.
  3. Each call to counter() adds 1 to count and returns it.

Normally a local variable is gone when its function ends. Here count stays alive, because the returned function still uses it. It also keeps its value between calls, which is why you see 1, 2, 3 and not 1, 1, 1.

The count is private

count is local to makeCounter, so code outside cannot see it:

print(count)

Output:

nil

Outside the function, count is just an unknown global name, so it is nil. The only way to change the real count is to call counter(). No other part of the program can reset it or set it to a wrong value by mistake.

Each call makes a new counter

Every call to makeCounter creates a new count variable and a new function that uses it. So two counters keep separate counts:

local a = makeCounter()
local b = makeCounter()

a()
a()
print("a:", a())
print("b:", b())

Output:

a:	3
b:	1

a was called three times, so its count is 3. b has its own count, which started at 0, so its first call returns 1.

Parameters are local variables too, so the inner function can also use the outer function's parameters. In the exercise, makeCounter takes a step value, and you complete the inner function so each call adds that step to the count.