Summary
In this lesson, you learned that:
- A function is a named piece of code that you write once and run as many times as you need. You define it with
local function name() … end, and you call it with its name and parentheses:name(). A function exists only from the line where it's defined; calling it earlier givesattempt to call a nil value (global 'name'). - A parameter is a name in the definition, an argument is a value in the call:
local function plant(crop, count),plant("carrots", 12). Arguments go into parameters in order. A missing argument isnil, and extra ones are ignored. returngives a value back to the place of the call and ends the function.printonly shows a value; a function withoutreturngivesnil. A function that calculates something should return the result.return a, breturns several values:local boxes, left = packEggs(20). A call gives all its values only as the last item of a list.- A default value is filled in at the start of the function:
bags = bags or 1. For a parameter that can befalse, checkif x == nil then. - A local variable exists from its line to the end of its block, and a function sees the local variables created above it. A variable without
localis global: a typo quietly creates a new one, and any function can overwrite it. That's why every variable and every function islocal. - A function is a value: you can store it in a variable and pass it to another function, without parentheses.
function(x) … endwithout a name is an anonymous function. table.sort(t, function(a, b) return a > b end)sorts by your rule: the function returnstruewhenacomes beforeb, andfalsefor equal items. Items that the rule considers equal can end up in any order, so add a second rule when it matters.- A closure is a function that remembers the local variables of the function that created it, such as the
countof a counter. error("message")stops the program withmain.lua:N: message(error(message, 0)without the position), andassert(condition, message)does the same when the condition isn't true.pcall(f, …)catches the error: it returnstrueand the results, orfalseand the message.
In the next lesson, you'll use tables in a new way: as dictionaries, which store values under names instead of numbers, such as how many of each crop is in the barn.
Instructions
Let's practice. Write a function totalAndBest with a parameter list that returns two values: the sum of the list and its largest number. Use it for sales and for the list {5, 9, 3}. The program prints:
Total: 142, best: 48
Total: 17, best: 9Write a function withBonus with the parameters amount and percent. It returns amount plus percent percent of it, rounded down with //: amount + amount * percent // 100. The default value of percent is 10. Print withBonus(142) and withBonus(142, 50). The program prints 156 and 213.
Sort sales from the best day to the worst with a comparison function, and print them joined with spaces. The program prints 48 35 27 20 12.
Start programming for free
11/11