Codectionary / Developer documentation / Lua

Lua Functions & Closures

Functions are first-class values in Lua: they can be stored, passed, and returned. A nested function can close over a local variable from its surrounding scope.

Syntax

local function add(left, right)
  return left + right
end

Examples

Creating a counter closure

A small, runnable example of this syntax.

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

local next_count = make_counter()
print(next_count())  -- 1
print(next_count())  -- 2

Best practices

  • Prefer local function declarations for named helpers so they do not leak into the global environment.
  • Keep examples small while learning, then combine the idea with a real project.

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

Specifications & further reading