Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 32 ยท Functions

Functions

Define and call Lua functions, pass parameters, return several values at once, understand value adjustment, and use the call syntax shortcuts.

A function is a named piece of code you can run whenever you like, with different inputs each time. Functions are how you avoid copying and pasting, how you give names to ideas, and, in Lua, how you build almost everything else. Lua treats functions as ordinary values, like numbers and strings, which opens up techniques you will see in the next lesson.

This lesson covers the basics: defining and calling functions, parameters, return values, Lua's unusual multiple returns, the rules for adjusting the number of values, and the call syntax shortcuts. Lua is not installed on this site, so the Lua listings are read-only (they are real Lua, with output taken from the semantics of Lua 5.4) and the runnable examples are JavaScript stand-ins.

Defining and calling

A function definition starts with the word function, a name, a parameter list in parentheses, a body, and end:

LUA
local function greet(name)
  print("Hello, " .. name .. "!")
end

greet("Ada")      --> Hello, Ada!
greet("Linus")    --> Hello, Linus!

Prefer local function unless you really want the function to be visible everywhere. Without local, the function is stored in a global variable, which any file in the program can read or overwrite. The word local limits the function to the block it was defined in. Variables and scope were introduced in Variables and Types.

Because functions are values, the definition above is really shorthand. These two forms do the same thing:

LUA
local function square(x) return x * x end

local square2 = function(x) return x * x end   -- an anonymous function stored in a variable

The second form shows that the function has no built-in name at all. The variable holds it, and you could store the same function in several variables.

Parameters and arguments

Parameters are the names in the definition. Arguments are the values you pass in a call. Lua is relaxed about how many you pass:

  • extra arguments are discarded
  • missing arguments become nil
LUA
local function show(a, b)
  print(a, b)
end

show(1, 2)       --> 1   2
show(1)          --> 1   nil
show(1, 2, 3)    --> 1   2      (the 3 is ignored)

There is no built-in way to declare default values, but the or operator gives you one: b = b or 10 replaces a missing b with 10. It also replaces an explicit false, so use it only when false is not a meaningful input. For functions that take any number of arguments, see Varargs and Closures.

Returning values

return ends the function and hands back results. A function with no return gives back nothing. One rule trips people up: return must be the last statement in its block. To return early, wrap it in an if, or put it in a do ... end block:

LUA
local function sign(n)
  if n < 0 then
    return -1          -- fine: last statement of the if block
  end
  if n > 0 then
    return 1
  end
  return 0
end

print(sign(-8), sign(0), sign(3))   --> -1   0   1

Multiple return values

Lua functions can return more than one value, separated by commas. This replaces the tuples, out-parameters, and small result objects you may know from other languages:

LUA
local function minmax(a, b)
  if a < b then
    return a, b
  else
    return b, a
  end
end

local low, high = minmax(9, 4)
print(low, high)    --> 4   9

The standard library uses this everywhere. string.find returns the start and end positions of a match, and math.modf returns the whole and fractional parts of a number. A caller who does not care about the second value just ignores it.

Adjusting values

Lua adjusts the number of values to fit wherever they are used:

  1. In an assignment with fewer variables than values, the extras are dropped. With more variables, the extras are nil.
  2. In an argument list or a table constructor, a function call that is the last item expands to all of its results. In any other position it is cut down to one value.
  3. Wrapping a call in parentheses forces exactly one value.
LUA
local function three() return 1, 2, 3 end

local a, b = three()          -- a=1, b=2 (3 is dropped)
local x, y, z, w = three()    -- w is nil

print(three())                --> 1   2   3   (last item: expands)
print(three(), "end")         --> 1   end     (not last: only the first value)
print("start", three())       --> start   1   2   3
print((three()))              --> 1           (parentheses truncate)

local list = {three(), three()}   -- {1, 1, 2, 3}: first call cut to 1, last expands

Rule 2 explains a classic surprise. {f()} collects all results of f into a list, while {f(), nil} collects only one.

What a function can do

Take parameters Missing ones are nil, extras are dropped.
Return values Zero, one or many.
Be a value Store it, pass it, return it.
1 / 2

Try it: multiple returns

JavaScript has one return value, so the stand-in returns an array and spreads it. The adjust helper models rule 2: only a call in the last position keeps all its values.

JS Multiple returns stand-in (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Call syntax shortcuts

When a function takes exactly one argument that is a string literal or a table constructor, the parentheses may be left out:

LUA
print "hello"                -- same as print("hello")
local config = load_config {path = "app.cfg", strict = true}
-- same as load_config({path = "app.cfg", strict = true})

You will see this style in configuration files and game scripts, because it reads like a declaration. It works only with a single literal; print "a", "b" is a syntax error.

The other shortcut is the method call with a colon: obj:name(args) means obj.name(obj, args). It passes the object as a hidden first argument called self. Calling s:upper() on a string is the same as string.upper(s):

LUA
local s = "lua"
print(s:upper())             --> LUA
print(string.upper(s))       --> LUA
print(("lua"):rep(3))        --> lualualua

Method calls are the foundation of objects in Lua, which you will build in Objects and Classes.

Passing and storing functions

Since a function is a value, you can pass it to another function. Here apply calls any function it is given, twice:

LUA
local function apply(f, x)
  return f(f(x))
end

print(apply(square, 3))                   --> 81
print(apply(function(n) return n + 1 end, 5))   --> 7

The second call passes an anonymous function directly. This pattern is behind sorting with a custom comparison, callbacks in game engines, and the iterators you saw in Iterating with pairs and ipairs.

Try it: functions as values

JS Functions as values (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when you call f(1) and f is defined as function f(a, b)?

    Missing arguments become nil. Extra arguments are silently discarded.
  2. 2. What does print(three(), "end") show when three returns 1, 2, 3?

    A call that is not the last item in a list is cut down to its first value.
  3. 3. Which is a valid early return in Lua?

    return must be the last statement of its block, but an if block counts, so early returns work as usual.
  4. 4. What does obj:method(x) mean?

    The colon passes the object as the hidden first parameter, conventionally named self.

Summary

  • Define functions with local function name(params) ... end, or store an anonymous function(...) ... end in a variable.
  • Missing arguments are nil; extra arguments are dropped.
  • return must be the last statement in its block, and a function may return several values.
  • A call expands to all its results only as the last item of a list; elsewhere it is cut to one value, and (f()) forces one.
  • f"text" and f{...} drop the parentheses; obj:name(...) passes obj as self.
  • Functions are values: store them, pass them and return them.

Next, functions that take any number of arguments and remember their surroundings in Varargs and Closures.