Syntax
local function make_counter()
local count = 0
return function() count = count + 1; return count end
endExamples
Two independent counters
Each call to make_counter creates its own count. Calling the returned function advances that counter. Expected output: 1, 2, 1 on separate lines.
local function make_counter()
local count = 0
return function()
count = count + 1
return count
end
end
local first = make_counter()
local second = make_counter()
print(first()) -- 1
print(first()) -- 2
print(second()) -- 1Callbacks that share state
Both returned functions use the same enabled variable. A closure sees changes to that variable; it does not freeze its initial value. Expected output: Hello, then Back. The middle call prints nothing.
local function make_logger()
local enabled = true
local function log(message)
if enabled then print(message) end
end
local function set_enabled(value)
enabled = value
end
return log, set_enabled
end
local log, set_enabled = make_logger()
log("Hello")
set_enabled(false)
log("Hidden")
set_enabled(true)
log("Back")Best practices
- Create the closure once when you need it to retain state. Calling make_counter() for every increment creates a new counter each time.
- Use local for captured state so unrelated code does not overwrite a global variable.
- Use a closure for a small callback with private state. A table can be clearer when callers need to inspect several named fields.
- Captured objects remain reachable while the closure uses them. Avoid retaining large tables in callbacks that outlive their task.
Runtime & versions
Lua interpreter or a host application. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Lua reference manuals