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.

At a glance

Purpose
Lightweight scripting and embedding
File extension
.lua
Runs in
Lua interpreter or a host application
Usually used with
Host APIs and Lua modules

Specifications & further reading

Related Lua documentation