Lesson 5 of 8 · 8 min

Functions

local function greet(name, greeting)
  greeting = greeting or "Hello"      -- a default value
  return greeting .. ", " .. name
end

print(greet("Ana"))            -- Hello, Ana
print(greet("Tino", "Mhoro"))  -- Mhoro, Tino

A missing argument is nil, so greeting or "Hello" gives a default.

Several return values

A Lua function can return more than one value:

local function divide(a, b)
  return a // b, a % b
end

local q, r = divide(17, 5)   -- q = 3, r = 2

Any number of arguments

... collects all the arguments. Put them in a table with {...}:

local function sum(...)
  local total = 0
  for _, n in ipairs({...}) do total = total + n end
  return total
end
print(sum(1, 2, 3))   -- 6

Functions are values

Functions can be stored in variables, passed to other functions and returned from them. A returned function remembers the variables around it (a closure):

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

Your task

  1. min_max(...): return the smallest and the largest of any number of arguments.
  2. apply_twice(f, x): return f(f(x)).
  3. make_multiplier(factor): return a function that multiplies its argument by factor.
main.lua
local function min_max(...)
end

local function apply_twice(f, x)
end

local function make_multiplier(factor)
end

print(min_max(3, 8, 1))

Lua 5.4 runs right here in your browser. The first run downloads about 0.4 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…