Functions

Functions are blocks of code that you can execute multiple times on command. You can also connect them to events or assign them as callbacks.

Basic Functions

A function definition includes:

  • The scope of the function (global or local).
  • The function keyword.
  • The name of the function in camelCase.
  • The parameters of the function in parentheses (()).
  • The block of code, or "body", of the function.
  • The end keyword.

The body of the function executes when you call the function. To call a function, type its name followed by parentheses. You can define a variable to accept the return value or use the return value in place of a variable.


1-- This function has no parameters and returns nil
2local function addOneAndTwo()
3 local result = 1 + 2
4 print(result)
5end
6-- Calling a function without a return
7addOneAndTwo() -- 3
8

Parameters

Parameters are variables that you make available to the function and are only used in the function's scope. Functions have no parameters by default. If you call a function with more parameters than it expects, Luau ignores the extra parameters. If you call a function with fewer parameters than it expects, Luau passes nil for all missing parameters.


1-- This function has two parameters: num1 and num2
2local function addNumbers(num1, num2)
3 print(num1 + num2)
4end
5
6addNumbers(2, 3) -- 5
7addNumbers(5, 6, 7) -- 11
8addNumbers(9) -- attempt to perform arithmetic (add) on number and nil
9

Return

In the body of the function, the return keyword returns a result from a computation. You can return multiple values from one function. return ends function execution, and Luau expects the end keyword to follow the return statements, so writing code between the return command and the end command throws an error.


1-- This function returns one return value
2local function addNumbers(num1, num2)
3 local result = num1 + num2
4 return result
5end
6
7print(addNumbers(1, 2)) -- 3
8local seven = addNumbers(3, 4)
9print(seven) -- 7
10
11-- This function returns multiple values: sum and difference
12local function addAndSubtract(num1, num2)
13 local sum = num1 + num2
14 local difference = num1 - num2
15 return sum, difference
16end
17
18-- Calling a function and expecting multiple return values
19local sum, difference = addAndSubtract(2, 3)
20print(sum) -- 5
21print(difference) -- -1
22

Methods

Methods are functions that are members of an object, such as a class or table. They expect the object itself (self) as the first argument. When you call a method, use the colon notation (:) instead of dot notation (.) to pass self as the first argument automatically.

All objects in Roblox descend from Instance and have commonly used methods including Instance:Destroy(), Instance:Clone(), and Instance:FindFirstChild().


1-- Destroying a Part with dot notation (function)
2local firstPart = Instance.new("Part")
3firstPart.Parent = workspace
4print(firstPart.Parent) -- Workspace
5firstPart.Destroy(firstPart)
6print(firstPart.Parent) -- nil
7
8-- Destroying a Part with colon notation (method)
9local secondPart = Instance.new("Part")
10secondPart.Parent = workspace
11print(secondPart.Parent) -- Workspace
12secondPart:Destroy()
13print(secondPart.Parent) -- nil
14

Defining Methods

To create a method in a table, use the name of the method as the key and the method function as the value. In the definition of the method, the self parameter refers to the method's parent table. When you call a method using colon notation, you pass the table itself as the first argument. You can define parameters for a method, but you need to list them after the self parameter.

In the following example, the testButton table has a method as the value of the changeEnabled key. You can verify that self refers to the method's parent table by printing the value of self.enabled.


1local testButton = {
2 enabled = true,
3 changeEnabled = function(self, isEnabled)
4 self.enabled = isEnabled
5 print(self.enabled)
6 end
7}
8
9print(testButton.enabled) -- true
10-- Call the method
11testButton:changeEnabled(false) -- false
12

Callbacks

Callbacks are functions that execute in response to another function or process. Some Global.RobloxGlobals functions, such as delay() and spawn(), take callbacks as parameters. In the Roblox Studio API, callbacks are write-only members of some classes. Unlike event handlers, callbacks yield until they return. Widely used callbacks include:

Setting Callbacks

To set a callback, assign a function to it. For example, BindableFunction.OnInvoke is a callback of BindableFunction. You can set a named or anonymous function to it, and you can call (invoke) that function by calling the :Invoke() method on the callback. The arguments you pass to :Invoke() forward to the callback, and the return value from the callback function returns to the caller of :Invoke().


1local bindableFunction = Instance.new("BindableFunction")
2
3bindableFunction.OnInvoke = function(number)
4 return 2 * number
5end
6
7print(bindableFunction:Invoke(42)) -- 84
8

Function Techniques

Event Handlers

You can assign a function, known as an event handler, to execute when an event fires. For example, you can create a function called onPlayerAdded() to the Players.PlayerAdded event to print the name of whatever player joins. For more information, see Events.


1local Players = game:GetService("Players")
2
3local function onPlayerAdded(player)
4 print(player.Name .. " joined the game!")
5end
6
7Players.PlayerAdded:Connect(onPlayerAdded)
8

Anonymous Functions

You can create functions without names, known as anonymous functions, to use as callbacks and event handlers. Like named functions, anonymous functions need to start and end with the function and end keywords, but you don't need the local keyword to indicate local scope because they always have local scope.

In the following example, the callback for the global delay() function and the event handler for the Players.PlayerAdded event are both anonymous functions.


1-- Anonymous function in a callback to delay()
2delay(2, function(exactTimeElapsed)
3 print(exactTimeElapsed) -- 2.0064592329945
4end)
5
6-- Anonymous function in an event handler
7local Players = game:GetService("Players")
8Players.PlayerAdded:Connect(function(player)
9 print(player.Name .. " joined the game!")
10end)
11

Functions in ModuleScripts

You can reuse functions across multiple scripts by storing them in ModuleScripts. Functions are a Luau data type, so you can store them in tables with other data. For more information, see ModuleScripts.

Variadic Functions

A variadic function accepts any number of arguments. For example, print() is a variadic function.


1print(2, "+", 2, "=", 2+2) --2 + 2 = 4
2print( string.format("The %s is a %s!", "cake", "lie") ) -- The cake is a lie!
3print( string.byte(115, 101, 99, 114, 101, 116) ) -- secret
4

Defining Variadic Functions

To define a variadic function, you use the ... token as the last or only parameter (not to be confused with .., the concatenation operator). You can put the ... values in a table for ease of use.


1local function variadic(named, ...)
2 local arguments = {...} -- pack the extra arguments into a table
3 print("Named argument = ", named)
4 for i, value in ipairs(arguments) do
5 print("Input No. ", i, "=", value)
6 end
7end
8
9variadic(10, "Hi", 20, "Variadic Function")
10--[[ Resulting output:
11Named argument = 10
12Input No. 1 = Hi
13Input No. 2 = 20
14Input No. 3 = Variadic Function
15]]
16

Argument Forwarding

You can define variadic functions as wrappers around other functions to pass, or forward, arguments from the wrapper to the other functions.


1local function printAround(functionToPrintAround, ...)
2 print("Before")
3 functionToPrintAround(...)
4 print("After")
5end
6
7local function addNumbers(x, y, z)
8 print("x =", x)
9 print("y + z =", y + z)
10end
11
12printAround(addNumbers, 1, 2, 3)
13--[[ Resulting output:
14Before
15x = 1
16y + z = 5
17After
18]]
19

Calling a Variadic Function with Arrays

If you want to pass a table array of values to a global variadic function, such as print(), you can use the use the global unpack() function to pass the values of the table instead of the table itself.


1local squares = {1, 4, 9, 16, 25}
2print( "The first 5 square numbers are:", unpack(squares) )
3-- The first 5 square numbers are 1 4 9 16 25
4