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:
local function lineTotal(quantity, price)
return quantity * price
end
lineTotal(100, 0.5) --> 50.0
lineTotal(3, 2) --> 6Declare 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.
input = { small = 500, large = 1000 }Steps
- Return
small: the price ofinput.smallitems at 0.12 each. - Add
large: the price ofinput.largeitems at the same rate. - 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.