Defining and Calling Functions
Syntax for function declaration, calling conventions, and local vs global functions.
Function Syntax
Functions in Lua are defined with the function keyword. The body is a block terminated by end. Functions can be global or local. You call a function by appending parentheses with arguments. If you omit arguments, missing parameters receive nil.
function sayHello(name)
print("Hello, " .. (name or "World") .. "!")
end
sayHello("Lua") -- Hello, Lua!
sayHello() -- Hello, World!
local function add(a, b)
return a + b
end
print(add(3, 4)) -- 7Return Values
Functions return values with return. Unlike most languages, Lua functions can return multiple values. If you don't explicitly return, the function returns nothing (zero values). Excess return values are discarded when the call is not the last expression in a list.
local function minMax(t)
local lo, hi = t[1], t[1]
for i = 2, #t do
if t[i] < lo then lo = t[i] end
if t[i] > hi then hi = t[i] end
end
return lo, hi
end
local lo, hi = minMax({5,2,8,1,9})
print(lo, hi) -- 1 9All lessons in this course
- Defining and Calling Functions
- Multiple Return Values
- Varargs and the ... Operator
- Recursion in Lua