Learn Lua · Functions · Lesson 1 of 3

Writing functions

A function is a piece of code with a name that you can run again with different values. Declare it with local function, list what it takes in brackets, and give back a result with return:

LUA
local function lineTotal(quantity, price)
  return quantity * price
end
lineTotal(100, 0.5)  --> 50.0
lineTotal(3, 2)      --> 6

Declare a function before the code that uses it. Writing the rule once means every caller gets the same answer, and a change only happens in one place.

What your code receives

Your code gets its data as input. The type Input line at the top of the code lists every field, and the editor uses it to suggest field names and spot typos. Here is an example. Each check sends different values, so work from the fields rather than these exact values.

LUA
input = { small = 500, large = 1000 }

Steps

  1. Return small: the price of input.small items at 0.12 each.
  2. Add large: the price of input.large items at the same rate.
  3. Charge at least 10 for any order: use 10 when the price works out lower.
Show a hint

Write local function priceFor(quantity) that does the sum and the minimum, then call it twice.