TExcelTAD
Home › Lua › Lua Functions

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.

lua · try it yourself
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:

lua · try it yourself
-- 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:

lua · try it yourself
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 ignored
Zoe 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:

lua · try it yourself
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 default doesn't work when false is a valid value, because false or default gives the default. Check if x == nil then x = default end instead.

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:

lua · try it yourself
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:

lua · try it yourself
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.

lua · try it yourself
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?

  1. An error
  2. Missing parameters are nil
  3. Missing parameters are 0
  4. The function is not called

What does function m.f() end do?

  1. Creates a local f
  2. Stores a function in field f of table m
  3. Declares a method with self
  4. Is a syntax error

What is the usual idiom for a default parameter value?

  1. function f(x = 5)
  2. x = x or 5
  3. default x = 5
  4. x ?= 5