Lua Functions
A function is a named block of code that runs only when it is called. Grouping steps into a function lets a program reuse those steps without writing them again.
One greet function, called twice
greet is defined once. Each call runs the body again, so the line prints twice.
local function greet()
print("Hello from Lua")
end
greet()
greet()A local variable inside a function
showTotal builds a local total each time it runs. The call prints the finished total.
local function showTotal()
local total = 40 + 2
print(total)
end
showTotal()Two functions run in call order
first is defined before second. The calls run second first, and the output order proves it.
local function first()
print("first runs")
end
local function second()
print("second runs")
end
second()
first()Example
local function header()
print("Weekly Report")
print("=============")
end
local function line()
print("Sales are up")
end
header()
line()
line()Key points
- Definition: the word function, a name, parentheses, a body, and end create a function.
- Call: writing the function name with parentheses runs its body.
- Order: Lua reads a program from top to bottom, so define a function before the line that calls it.
- Local: local function stores the function in a local variable, and that is the usual habit.
- Reuse: one function can be called many times, from many different lines.
In this example, header prints the report title and its underline. The line function then runs twice, so its sentence appears two times under the header.
Note
a call placed above its definition fails, because the function does not exist yet at that line.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line actually runs the body of a function named greet?