Skip to content
Closures
step 1/5

Reading — step 1 of 5

Learn

~1 min readFunctions

Lua functions are closures — they capture surrounding local variables (called upvalues).

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

local c = counter()
print(c())   -- 1
print(c())   -- 2
print(c())   -- 3

Each call to counter() creates a fresh count upvalue. The returned function holds a reference to it.

Closures are how you build iterators, callbacks, partial application, and module-private state in Lua. Almost all of Lua's expressive power comes from this single feature.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…