When a function is called, it can contain a comma-separated list of values between parenthesis, these are arguments. They are assigned to parameters based on the order in the function declaration.
function printNumbers(x, y)print("Your first number is: " .. x)print("Your second number is: " .. y)end-- 3 and 25 are our argumentsprintNumbers(3, 25)-- Prints:-- Your first number is 3-- Your second number is 25
Functions are declared using their name, which can be used to call the function later. Function declarations are built from:
function
keyword ()
end
keyword as the last line of the functionfunction printFavoriteColor(color)print("Your favorite color is " .. color)end
A function is a set of statements that are executed together when called using the function’s name.
function getTallestMountain()print("The tallest mountain is Mount Everest")end
A function can return, or pass back, values using the return
keyword. Return ends function execution and returns the specified value to where the function was called.
function double(x)return 2 * xenddoubledX = double(2)print(doubledX) -- Prints: 4
Lua’s built-in functions are all documented on Lua’s official website. For additional examples of these functions, the user-maintained documentation is also useful.
When a function is declared it can contain parameters as inputs. These act as variables inside the function. These parameters are only assigned a value when the function is called.
function printNumber(number)print("Your number is: " .. number)end
Functions can be called after they have been declared using the function’s name followed by parenthesis. When called, all the code inside the function’s declaration is run.
function printSquare(num)print(num * num)endprintSquare(4) --Prints: 16printSquare(2) --Prints: 4printSquare(16) --Prints: 256
If a function is called without passing in enough arguments, the nil
value is assigned to the remaining parameters.
function printAge(age)print("You are " .. age .. " years old")endprintAge() -- Prints: You are nil years old
Lua has several built-in functions. Most are automatically included and can be called with no additional code. Some built-in functions include the print()
and type()
functions.