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
min_max(...): return the smallest and the largest of any number of arguments.apply_twice(f, x): returnf(f(x)).make_multiplier(factor): return a function that multiplies its argument byfactor.