LUA / CHAPTER 03

Functions, locals, and return values

Beginner

Package calculations while making scope and results explicit.

By the end of this chapter

  • Create local functions
  • Trace parameter bindings
  • Capture multiple return values

The idea

A function is a value that can be stored in a variable, passed to another function, or returned as a result. Define a local function when its name belongs to one block or module. Parameters are local variables initialized from the call’s arguments. Reassigning a numeric parameter does not change the caller’s variable. A return statement ends the current call and sends results back to its caller.

Lua functions can return several values, and an assignment can capture them in separate variables. Missing results become nil. This is useful for returning a useful value together with an explanation of failure. Keep each result’s meaning stable across successful and unsuccessful paths. Names inside a local block can shadow outer names, so inspect the nearest visible declaration when tracing a program.

Lua example
local function divide(a, b)
  if b == 0 then return nil, "zero divisor" end
  return a / b, nil
end
local value, problem = divide(8, 0)
print(value == nil)
print(problem)
Result
true
zero divisor

The early return produces two results. The caller receives absence in value and a diagnostic string in problem, without attempting division.

Try it yourself

Return the smaller and larger of two numbers as two results, including equal inputs.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does this print?
local x = 5
local function change(x) x = x + 2; return x end
print(change(x))
print(x)