Functions | Documentation - Roblox Creator Hub (2024)

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.

-- This function has no parameters and returns nil

local function addOneAndTwo()

local result = 1 + 2

print(result)

end

-- Calling a function without a return

addOneAndTwo() -- 3

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.

-- This function has two parameters: num1 and num2

local function addNumbers(num1, num2)

print(num1 + num2)

end

addNumbers(2, 3) -- 5

addNumbers(5, 6, 7) -- 11

addNumbers(9) -- attempt to perform arithmetic (add) on number and nil

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.

-- This function returns one return value

local function addNumbers(num1, num2)

local result = num1 + num2

return result

end

print(addNumbers(1, 2)) -- 3

local seven = addNumbers(3, 4)

print(seven) -- 7

-- This function returns multiple values: sum and difference

local function addAndSubtract(num1, num2)

local sum = num1 + num2

local difference = num1 - num2

return sum, difference

end

-- Calling a function and expecting multiple return values

local sum, difference = addAndSubtract(2, 3)

print(sum) -- 5

print(difference) -- -1

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().

-- Destroying a Part with dot notation (function)

local firstPart = Instance.new("Part")

firstPart.Parent = workspace

print(firstPart.Parent) -- Workspace

firstPart.Destroy(firstPart)

print(firstPart.Parent) -- nil

-- Destroying a Part with colon notation (method)

local secondPart = Instance.new("Part")

secondPart.Parent = workspace

print(secondPart.Parent) -- Workspace

secondPart:Destroy()

print(secondPart.Parent) -- nil

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.

local testButton = {

enabled = true,

changeEnabled = function(self, isEnabled)

self.enabled = isEnabled

print(self.enabled)

end

}

print(testButton.enabled) -- true

-- Call the method

testButton:changeEnabled(false) -- false

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:

  • MarketplaceService.ProcessReceipt, which handles developer products purchases.

  • BindableFunction.OnInvoke, which calls the function when a script calls BindableFunction:Invoke(...).

  • RemoteFunction.OnClientInvoke, which calls the function when the server calls RemoteFunction:FireClient(player, ...) or RemoteFunction:FireAllClients(...).

  • RemoteFunction.OnServerInvoke, which calls the function when a client calls RemoteFunction:InvokeServer(...).

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().

local bindableFunction = Instance.new("BindableFunction")

bindableFunction.OnInvoke = function(number)

return 2 * number

end

print(bindableFunction:Invoke(42)) -- 84

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 Built-In Events.

local Players = game:GetService("Players")

local function onPlayerAdded(player)

print(player.Name .. " joined the game!")

end

Players.PlayerAdded:Connect(onPlayerAdded)

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 task.delay() function and the event handler for the Players.PlayerAdded event are both anonymous functions.

-- Anonymous function in a callback to task.delay()

task.delay(2, function(exactTimeElapsed)

print(exactTimeElapsed) -- 2.0064592329945

end)

-- Anonymous function in an event handler

local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(player)

print(player.Name .. " joined the game!")

end)

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.

Variadic Functions

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

print(2, "+", 2, "=", 2+2) --2 + 2 = 4

print( string.format("The %s is a %s!", "cake", "lie") ) -- The cake is a lie!

print( string.char(115, 101, 99, 114, 101, 116) ) -- secret

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.

local function variadic(named, ...)

local arguments = {...} -- pack the extra arguments into a table

print("Named argument =", named)

for i, value in arguments do

print("Input No.", i, "=", value)

end

end

variadic(10, "Hi", 20, "Variadic Function")

--[[ Resulting output:

Named argument = 10

Input No. 1 = Hi

Input No. 2 = 20

Input No. 3 = Variadic Function

]]

Argument Forwarding

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

local function printAround(functionToPrintAround, ...)

print("Before")

functionToPrintAround(...)

print("After")

end

local function addNumbers(x, y, z)

print("x =", x)

print("y + z =", y + z)

end

printAround(addNumbers, 1, 2, 3)

--[[ Resulting output:

Before

x = 1

y + z = 5

After

]]

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 global unpack() function to pass the values of the table instead of the table itself.

local squares = {1, 4, 9, 16, 25}

print( "The first 5 square numbers are:", unpack(squares) )

-- The first 5 square numbers are 1 4 9 16 25

Functions | Documentation - Roblox Creator Hub (2024)

FAQs

How to trigger a function in Roblox? ›

Functions won't run until they are called. To call a function, type the function's name including the () at the end. Under end, type printFood(). print("Curry!")

What code do Roblox devs use? ›

Roblox uses the coding language Lua. This article will cover how to start coding in Roblox, introducing common concepts like scripts, data types, and variables.

How to connect functions in Roblox Studio? ›

Connecting Functions to Events

You connect a function to an event using Connect() to execute code each time the event fires. Most events pass arguments to their connected functions. For example, the BasePart. Touched event passes the object that touched the part (such as a left hand or car wheel), and the Players.

What is the difference between dot and colon in Roblox? ›

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().

What does F11 do in Roblox? ›

Interface Controls
ActionWindowsDescription
Quick Open ActionsAltCtrlPShow the Quick Open Actions window to quickly find any Studio action.
Studio SettingsAltSOpen the Studio settings window.
Full ScreenF11 AltF11Toggle between full screen and windowed view.
Video RecordF12Record a video; not functional on Mac.
7 more rows

What is the _g function in Roblox? ›

_G is a global array in Lua that can be used to share information across multiple scripts that are running at the same context level. For example, it might be useful to store a string for multiple scripts to use: -- Script 1 _G. MyInfo = "Hello, world!" -- Script 2 print(_G.

Does Roblox use C++? ›

Does Roblox use C++? Yes, Roblox does also use C++ as well as Lua. When kids code with Roblox, they will be using Lua in the Roblox Studio, but some of the software used for memory management in the background has been developed with C++.

Is Roblox coding easy? ›

Discover the Roblox programming language: Lua

It is known for its simplicity and ease of use, making it a popular choice for beginners and experienced programmers alike.

What is the very first Roblox game to reach 1B+ visits? ›

MeepCity was the first game on Roblox to pass 1 billion total visits.

What is the touched function in Roblox? ›

The Touched event fires when a part comes in contact with another part. For instance, if PartA bumps into PartB, then PartA. Touched fires with PartB, and PartB. Touched fires with PartA.

What is the wait function in Roblox? ›

Yields the current thread until the given duration (in seconds) has elapsed, then resumes the thread on the next Heartbeat step. The actual amount of time elapsed is returned.

How do you make a function module on Roblox? ›

To add a function or variable to the module which can be used in another script, type the module table's name, followed by a dot, and the name of the function or variable, like in TestModule. myVariable.

What does Roblox 13 mean? ›

13+ Content is generally suitable for ages 13 and up. May contain moderate violence, light realistic blood, moderate crude humor, and/or unplayable gambling content.

What is Roblox actually called? ›

The beta version of Roblox was created by co-founders David Baszucki and Erik Cassel in 2004 under the name DynaBlocks. Baszucki started testing the first demos that year. In 2005, the company changed its name to Roblox.

How to trigger an event in Roblox? ›

You can use a LocalScript to trigger an event on the server by calling the FireServer() method on a RemoteEvent. If you pass arguments to FireServer(), they pass to the event handler on the server with certain limitations.

What does function () do in Roblox? ›

Source. In Lua, a function is a block of code that can be called to perform a specific task and may be called multiple times. Functions can take arguments which are values provided by the call (simply known as inputs) and can return values to the call (simply known as outputs).

How do you call a module function on Roblox? ›

You can call the function by referencing to the function in the table itself. This can change depending upon what data you're returning from your module script. For example, if you're returning a function (instead of a table of functions) from the module script, then you can call the function straight away.

What is the F9 command in Roblox? ›

Opening the Console

You can open Developer Console during a testing or a live experience session using any of the following ways: Press F9. Type /console into the chat.

Top Articles
BlackBerry vs. the True Story of Mike Lazaridis and Jim Balsillie
Jim Balsillie Net Worth – Repeat Replay
Barstool Sports Gif
Is Paige Vanzant Related To Ronnie Van Zant
Cappacuolo Pronunciation
Trevor Goodwin Obituary St Cloud
Danielle Moodie-Mills Net Worth
Form V/Legends
Craigslist Portales
<i>1883</i>'s Isabel May Opens Up About the <i>Yellowstone</i> Prequel
Hallowed Sepulchre Instances &amp; More
Meg 2: The Trench Showtimes Near Phoenix Theatres Laurel Park
R Tiktoksweets
Jvid Rina Sauce
Huge Boobs Images
iOS 18 Hadir, Tapi Mana Fitur AI Apple?
Images of CGC-graded Comic Books Now Available Using the CGC Certification Verification Tool
Equipamentos Hospitalares Diversos (Lote 98)
2020 Military Pay Charts – Officer & Enlisted Pay Scales (3.1% Raise)
NBA 2k23 MyTEAM guide: Every Trophy Case Agenda for all 30 teams
The Menu Showtimes Near Regal Edwards Ontario Mountain Village
Outlet For The Thames Crossword
Webcentral Cuny
How to Grow and Care for Four O'Clock Plants
Jc Green Obits
Craigs List Tallahassee
Bolsa Feels Bad For Sancho's Loss.
Craigslist Rentals Coquille Oregon
Harrison 911 Cad Log
Viduthalai Movie Download
Federal Express Drop Off Center Near Me
Page 2383 – Christianity Today
Craigslist/Phx
Bursar.okstate.edu
Roadtoutopiasweepstakes.con
Baddies Only .Tv
20+ Best Things To Do In Oceanside California
Alpha Asher Chapter 130
D-Day: Learn about the D-Day Invasion
Wayne State Academica Login
Rhode Island High School Sports News & Headlines| Providence Journal
'Guys, you're just gonna have to deal with it': Ja Rule on women dominating modern rap, the lyrics he's 'ashamed' of, Ashanti, and his long-awaited comeback
Locate phone number
Pink Runtz Strain, The Ultimate Guide
Shell Gas Stations Prices
Flappy Bird Cool Math Games
Autozone Battery Hold Down
Babykeilani
Walmart Listings Near Me
Razor Edge Gotti Pitbull Price
Sj Craigs
How to Choose Where to Study Abroad
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 6261

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.