Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What does connect(function(function_name) actually do?

Asked by 3 years ago

Hello, thanks for your coming. I wonder what does connect(function() do, cause I have checked a lot of tutorials and it contains a lot of this script but I do not know what is it used for.

1 answer

Log in to vote
0
Answered by
Ziffixture 6913 Moderation Voter Community Moderator
3 years ago
Edited 3 years ago

What you're seeing is what's known as an RBXScriptSignal. These are the objects that allow us to use ROBLOX's Event system.

Almost every Instance available to you contains Events that the programmer can attach callbacks to. This is achieved via the :Connect() method.


(function() is commonly mistaken as a unique part of setting up a listener, when in reality, it's simply programmers creating what's known as anonymous functions. As said above, :Connect() accepts a function Object to be executed upon the signal firing, in most cases, we create these callbacks when passing them through as the argument:

Instance.RBXScriptSignal:Connect(function()
    print("Hello!")
end)

--// In reality ^

Instance.RBXScriptSignal:Connect(
    ---------------
    function()
        print("Hello!")
    end
)

---------------

--// Can be handled like so:

local function Hello()
    print("Hello")
end


Instance.RBXScriptSignal:Connect(Hello)

Let's demonstrate the use of this, by running a function to print the Player's name who has just joined the game!

We will use the .PlayerAdded signal of Players to achieve this:

local Players = game:GetService("Players")


local function GreetPlayer(Player)
    print(Player.Name)
end


Players.PlayerAdded:Connect(GreetPlayer)

Note:

RBXScriptSignals can pass arguments to your functions depending on their purpose, it's wise to read the documentation of certain Events to determine their possible parameters. You can see how the Player parameter was listed in the API-Reference hyperlink.

0
got it! willywillycow 50 — 3y
1
This taught me more about events! Thank you! FrontsoldierYT 129 — 3y
Ad

Answer this question