Lua · Course navigation

Lua Functions

Write a local function that loops over a table and returns a result.

On this page
Before you start

Lua tables.

  • Write a local function that loops over a table and returns a result.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

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.

Code example

Lua
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})))
Output
86

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1local function average(values)
2 local total = 0
3 for _, v in ipairs(values) do
4 total = total + v
5 end
6 return total / #values
7end
8
9print(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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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

Behind the scenes

How Lua processes this code

The Lua interpreter executes the chunk and resolves local values as it runs.

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.

Further reading