Lua Functions
Write a local function that loops over a table and returns a result.
local function average(values)
local total = 0
for _, v in ipairs(values) do
total = total + v
end
return total / #values
end
print(math.floor(average({82, 91, 76, 95})))86
Explanation
Functions are first-class values in Lua. local function average(values) declares a function visible in its scope, and return sends back a result. ipairs walks the array part of a table in order, giving each index and value; _ names an index we do not need.
The / operator always does floating-point division. Lua 5.3 and later prints a float with a trailing .0 (86.0) while Lua 5.1 prints 86, so the example wraps the result in math.floor to get the same whole number everywhere.
Explore the dry run
local function average(values) local total = 0 for _, v in ipairs(values) do total = total + v end return total / #valuesend print(math.floor(average({82, 91, 76, 95})))Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Define a function with one parameter. | — | — | |
| Add the four scores one by one. | total = 344 | — | |
| Divide by the length, 4. | return = 86 | — | |
| Round down and print. | return = 86 | 86 |
Cost and common mistakes
O(n) time and O(1) extra space.
- Forgetting local makes a variable global, which any other code can change.
- An empty table divides by 0 and produces nan or inf instead of an error.
Try it yourself
Predict average({1, 2}) without math.floor on Lua 5.4.
Reveal answer and reasoning
It returns 1.5, because 3 / 2 uses floating-point division.