Functions

qI6473's avatar
Published Aug 9, 2023
Contribute to Docs

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.

Function Declaration

Functions are declared and called using their names. Function declarations are built using:

  1. The function keyword.
  2. The function’s name in camel case: the first word starts with lowercase, and any following words start with uppercase. For example: iPhone.
  3. An optional list of comma-separated parameters, enclosed by ().
  4. The code to be run by the function.
  5. The end keyword 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 - value2
print(result)
end

Parameters

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 parameters
result = number1 + number2
print(result)
end

Calling Functions

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 * 5
print(result)
end
product() -- This is calling a function

Arguments

When a function is called, a comma-separated list of values between parentheses are arguments.

function sum(number1, number2)
result = number1 + number2
print(result)
end
sum(30,20) -- 30 and 20 are arguments

Nil Arguments

When a function is called without passing in enough arguments, the remaining parameters will be assigned the value nil.

function sum(number1, number2)
result = number1 + number2
print(result)
end
sum() -- Throws an error because nil values can't be summed

Return Keyword

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 * number2
return result
end
total = product(2, 4)
print(total) -- Prints: 8

All contributors

Contribute to Docs

Learn Lua on Codecademy