Functions are blocks of code that can be repeated multiple times. They can perform specific tasks when they’re called. A function must be declared in the scope it will be utilized.
Functions are declared and called using their names. Function declarations are built using:
- The function’s name in camel case: the first word starts with lowercase, and any following words start with uppercase. For example: iPhone.
- An optional list of comma-separated parameters, enclosed by
- The code to be run by the function.
endkeyword in the last line of function.
The example code provided below contains a function named
difference() that takes two values and prints their difference:
function difference(value1, value2)result = value1 - value2print(result)end
When a function is declared, inputs can be provided as parameters. Parameters are only assigned a value when the function is called.
function sum(number1, number2) -- number1 and number2 are parametersresult = number1 + number2print(result)end
Functions can be called by referencing the function’s name followed by parentheses, once functions have been declared. Once called, all the code inside the function will run.
function product()result = 2 * 5print(result)endproduct() -- This is calling a function
When a function is called, a comma-separated list of values between parentheses are arguments.
function sum(number1, number2)result = number1 + number2print(result)endsum(30,20) -- 30 and 20 are arguments
When a function is called without passing in enough arguments, the remaining parameters will be assigned the value
function sum(number1, number2)result = number1 + number2print(result)endsum() -- Throws an error because nil values can't be summed
The output of the function can be specified using the
return keyword. This returns the value to where the function was called and ends the function.
function product(number1, number2)result = number1 * number2return resultendtotal = product(2, 4)print(total) -- Prints: 8