3. Functions
A function is a piece of code with a name. You write it once and run it from anywhere, as many times as you like.
You have used one already: print is a function.
Writing one
The first part defines the function. Nothing happens until it is called, with its name and a pair of brackets.
Arguments
A function can take values to work with. They are named in the brackets:
name is a local variable that exists only inside the function. It gets whatever the caller passed.
Several arguments are separated by commas:
An argument the caller leaves out is nil. or gives it a default:
Results
return hands a value back to the caller, and ends the function.
A function that returns a value can be used anywhere a value can.
return also leaves a function early. This is a common shape: deal with the cases that need nothing done, then do the work.
More than one result
A function can return several values, separated by commas:
Engine functions use this. Input.GetMouseDelta() returns two numbers, how far the mouse moved across and down:
Functions that come with Lua
Lua's math and string libraries are there in every script.
string.format is the tidy way to show a number with a fixed count of decimals, for a timer on screen.
The engine adds a few to math that games want constantly:
Functions are values
A function can be stored in a variable and passed to another function, like any value. The two ways of writing one mean the same:
This matters because the engine often asks for a function to run later. A timer takes one:
The function has no name. It is written right where it is needed and handed to Timer.After, which keeps it and calls it when the time comes.
Remembering what was around
A function can use the local variables that were in sight where it was written, even after that place has finished running:
count lives on inside the returned function. This is called a closure, and it is why the timer above can use variables from the code around it.
Where a variable can be seen
A local exists from the line that makes it to the end of the block it is in: the function, loop or if.
Because of this, a local function must be written above the code that calls it.
Try it
- Write
isEven(n)that returns true for an even number. Use it in a loop to print the even numbers up to 10. - Write
clampHealth(health)that returns the health kept between 0 and 100, without usingmath.clamp. - Write
stats(a, b, c)that returns the smallest and the largest of three numbers, and print both.
Next: tables.