Functions
Prerequisites: Tables: the one data structure
local function square(n)
return n * n
end
local function greet(name)
print("Hello, " .. name .. "!")
end
print(square(7))
greet("Ada")
print(greet("Linus"))
49
Hello, Ada!
Hello, Linus!
local function name(params) ... enddefines a function.returnsends a value back; a function withoutreturnreturns nothing (which becomesnilwhen used as a value).- Like variables, functions should be
local.
Arguments are flexible
local function describe(name, age)
return tostring(name) .. " / " .. tostring(age)
end
print(describe("Ada", 36))
print(describe("Ada"))
print(describe("Ada", 36, "extra"))
Ada / 36
Ada / nil
Ada / 36
Missing arguments become nil; extra ones are ignored. Lua never
complains about the number of arguments — check them yourself when it
matters.
Functions are values
local double = function(x) return x * 2 end
local function applyToAll(list, fn)
local result = {}
for i, v in ipairs(list) do
result[i] = fn(v)
end
return result
end
print(table.concat(applyToAll({1, 2, 3}, double), " "))
print(table.concat(applyToAll({1, 2, 3}, function(x) return x * x end), " "))
2 4 6
1 4 9
Functions can be stored in variables and tables, passed to other functions, and returned from them — the basis of callbacks, event handlers, and closures (Level 2).
Recursion
local function factorial(n)
if n <= 1 then return 1 end
return n * factorial(n - 1)
end
print(factorial(10))
3628800
local function f makes f visible inside its own body, so it can call
itself.
Practice
Write isEven(n) and use it to print the even numbers from 1 to 10.
Show solution
local function isEven(n)
return n % 2 == 0
end
for n = 1, 10 do
if isEven(n) then print(n) end
end
2
4
6
8
10