Lua Functions
A function is a named, reusable block of code. In Lua, functions are first-class values: you can store them in variables and tables, pass them to other functions and return them.
local function greet(name)
return "Hello, " .. name .. "!"
end
print(greet("Ada"))
print(greet("Linus"))Hello, Ada!
Hello, Linus!
Defining functions
There are three common forms, and they all create a function value:
-- 1. local function (preferred)
local function square(x) return x * x end
-- 2. anonymous function stored in a variable
local cube = function(x) return x * x * x end
-- 3. function stored in a table (a "method" of a module)
local geometry = {}
function geometry.circleArea(r)
return math.pi * r * r
end
print(square(4), cube(3), string.format("%.2f", geometry.circleArea(2)))
print(type(square))16 27 12.57
function
function geometry.circleArea(r) is shorthand for geometry.circleArea = function(r) … end. Without local, function name() … end creates a global function.
Parameters and arguments
Lua is relaxed about argument counts. Missing arguments become nil, extra ones are ignored:
local function describe(name, age)
return name .. " is " .. tostring(age)
end
print(describe("Zoe", 30))
print(describe("Zoe")) -- age is nil
print(describe("Zoe", 30, "extra")) -- "extra" is ignoredZoe is 30
Zoe is nil
Zoe is 30
Default values
There are no default-parameter declarations. The idiom is param = param or default at the top of the function:
local function makeTag(text, tag)
tag = tag or "p"
return "<" .. tag .. ">" .. text .. "</" .. tag .. ">"
end
print(makeTag("Hi"))
print(makeTag("Title", "h1"))<p>Hi</p>
<h1>Title</h1>
Note:
x = x or defaultdoesn't work whenfalseis a valid value, becausefalse or defaultgives the default. Checkif x == nil then x = default endinstead.
Named arguments with a table
When a function has many optional settings, pass a single table. Combined with the "no parentheses" call syntax, this reads like named arguments:
local function createWindow(opts)
local width = opts.width or 800
local height = opts.height or 600
local title = opts.title or "Untitled"
return string.format("%s (%dx%d)", title, width, height)
end
print(createWindow { title = "Editor", width = 1024 })
print(createWindow {})Editor (1024x600)
Untitled (800x600)
Functions as values
Because functions are values, you can put them in tables, pass them as arguments, and choose one at run time:
local operations = {
add = function(a, b) return a + b end,
mul = function(a, b) return a * b end,
}
local function apply(op, a, b)
return op(a, b)
end
print(apply(operations.add, 6, 7))
print(apply(operations.mul, 6, 7))
print(apply(math.max, 6, 7))13
42
7
return
return ends the function and gives back zero or more values. A function without return returns nothing, which becomes nil when used as a value. return must be the last statement in a block; write do return end if you need an early return in the middle of a block during debugging.
local function sign(x)
if x > 0 then return "positive" end
if x < 0 then return "negative" end
return "zero"
end
local function noReturn() end
print(sign(5), sign(-2), sign(0))
print(noReturn())
print(noReturn() == nil)positive negative zero
true
print(noReturn()) prints an empty line because the call returns no values at all, which is slightly different from returning nil. The varargs lesson explains why this matters.
Test yourself
What happens when you call a Lua function with fewer arguments than parameters?
- An error
- Missing parameters are
nil - Missing parameters are
0 - The function is not called
What does function m.f() end do?
- Creates a local
f - Stores a function in field
fof tablem - Declares a method with
self - Is a syntax error
What is the usual idiom for a default parameter value?
function f(x = 5)x = x or 5default x = 5x ?= 5