Learn/Lua/6. Functions
Lesson 6 of 8
Sign in

Lua, lesson 6

Functions

A function packs a piece of logic under a name so you can reuse it. In Lua you define one with function ... end:

  • local function makes the function local, just like local does for variables. Use it by default.
  • (n) is the parameter list. Lua doesn't check types, so any value can be passed.
  • return sends a value back to the caller and ends the function immediately.

A function must be defined before the line that calls it runs, because Lua executes the file from top to bottom. Put your functions near the top.

Several parameters

Lua is relaxed about argument counts. Missing arguments become nil, and extra ones are ignored. You can use that to give a parameter a default value:

Returning several values

A Lua function can return more than one value. List them after return, and catch them with several variables:

2 exercises to try what you just read.

Exercise 1

Shipping costs

Press Ctrl Enter or Check to test your code.

Exercise 2

Party bags

Press Ctrl Enter or Check to test your code.

A function with no return, or a bare return, gives back nothing (which reads as nil).

Scope

A local declared inside a function exists only inside that function, from the line where it's declared to the function's end. The same goes for parameters. That keeps functions independent: two functions can each have their own total.

Any block (do ... end, the body of an if or a loop) also starts a new scope for the locals inside it.

Recursion

A function can call itself. Because local function name makes the name visible inside its own body, recursion just works:

Functions are values

In Lua a function is a value like a number or a string. local function f() end is a short way of writing local f; f = function() end. You can store functions in variables, pass them to other functions, and return them. You'll use that with table.sort in the next lesson.

Further reading

  • Lua 5.5 Reference Manual: Function definitions
  • Lua 5.5 Reference Manual: Function calls
  • Lua 5.5 Reference Manual: Scopes, variables and environments

Write local function shipping_cost(weight) using these rules:

  • up to 1 kg: 5
  • up to 5 kg: 12
  • up to 20 kg: 25
  • over 20 kg: 25 plus 2 for every kg above 20

The first input line is the number of parcels. Each following line holds one whole-number weight. For each parcel print <weight> kg costs <cost>, then print Total: <sum>.

Sample input:

Sample output:

You have some candies and some stickers and want to fill as many identical party bags as possible, using everything. The number of bags is the greatest common divisor (GCD) of the two amounts.

Write a recursive local function gcd(a, b) using Euclid's rule: the GCD of a and 0 is a; otherwise the GCD of a and b equals the GCD of b and a % b.

Read the candies and the stickers (two whole numbers, at least 1, separated by a space) and print:

Sample input:

Sample output:

local function square(n)
  return n * n
end

print(square(7))   -- 49
local function price_with_tax(price, rate)
  return price + price * rate
end

print(price_with_tax(10, 0.2))   -- 12.0
local function greet(name, greeting)
  greeting = greeting or "Hello"
  return greeting .. ", " .. name .. "!"
end

print(greet("Ada"))              -- Hello, Ada!
print(greet("Ada", "Welcome"))   -- Welcome, Ada!
local function min_max(a, b)
  if a < b then
    return a, b
  end
  return b, a
end

local low, high = min_max(9, 4)
print(low, high)   -- 4<tab>9
local count = 10          -- visible to everything below

local function bump()
  local count = 1         -- a different variable that hides the outer one
  return count + 1
end

print(bump(), count)      -- 2<tab>10
local function factorial(n)
  if n <= 1 then return 1 end
  return n * factorial(n - 1)
end
3
1
4
23
1 kg costs 5
4 kg costs 12
23 kg costs 31
Total: 48
Bags: <n>
Each bag: <c> candies, <s> stickers
12 18
Bags: 6
Each bag: 2 candies, 3 stickers