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