Deeper understanding into :Connect(function(Something)

I wanted to understand how the function() thing works more.

I’ve seen people put function(player, character) or function(mouse, mousepos), etc. And I wanted to get a deeper understanding on what I can put in there, how it relates to the player character mouse or whatever.

I’ve already looked it up and it just explains what everything else does BESIDES that certain part. I haven’t experimented with it yet either.

All replies are greatly appreciated.

8 Likes

Essentially, you are creating a new function when connecting an event. For instance, look at this API:

https://developer.roblox.com/en-us/api-reference/event/UserInputService/InputBegan

The parameters are input and gameProcessedEvent. So essentially if you want values from those two variables, you’d have to set your code to be like this:

local UserInputService = game:GetService("UserInputService")

UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)

end)
4 Likes

What you put in there are all the arguments. For example, with the .Touched event on parts the first argument gives whatever the part touched, so if the part touched the baseplate, the argument would be the baseplate. All the events have different arguments. An example of the touched event though:

local part = ....

part.Touched:Connect(function(touching)
    print(part, "touched", touching)
end)
3 Likes

Every event that you connect a function to will return something when it fires. Here’s an example: BasePart.Touched. In a script, this would look something like

YourPart.Touched:Connect(function(otherPart)
	-- code here
end)

So when the Touched event fires (a.k.a. the part touches another part), you Connect the following function to it: -- code here
If you click on the article and scroll down to the “Parameters” part, you will see the parameters that the event has: “otherPart”, the BasePart (or normal part) that touched YourPart and made the event fire. This is what you have to write inside the brackets at the function. So if you write something like

YourPart.Touched:Connect(function(otherPart)
	otherPart.Color = Color3.new(1, 0, 0) -- the red color
end)

it will turn the otherPart that touched YourPart red. Note that these parameters can be named anything, only the order of them matters (also, you can’t name two parameters the same thing). You can even cut down the parameters and just write nothing inside the brackets if you don’t have to use them.

Another example: UserInputService.InputBegan. As you can see, there are 2 parameters this time, the input and the gameProcessedEvent. When the UnputBegan fires, meaning the player pressed down a button, you can get the button (or any other key) that was pressed down from the input parameter. Clicking on the “Type” of the parameter will open a detailed description of the object, such as how to get the button from the input.
The other parameter shows if the game engine has already acted on the input, but since you can cut down the parameters, it’s enough to only write the input and it will work totally fine.

There are also events that do not have any parameters, meaning you can’t / don’t have to write anything inside the brackets.

When working with Remote Events, you can make your own parameters that get passed between multiple server scripts and local scripts.

I hope you were able to understand me, but feel free to ask again any time :grinning:

3 Likes

I’ll be really honest this part of Roblox scripting just seemed straight forward and I didn’t take much notice at first.

Everything that I know about

:Connect()

I know that you will most likely :Connect to a function and I know it can be in these 2 various ways, first way:

local function printline(val1, val2) -- example function
return print("--------------", "\n ".. val1.KeyCode)
end

local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(printline) -- Edit thanks for the check @me_isidoit

--[[ To explain this, when you press something on your device it will
   then connect at your function that you provided in my case (printline).
But usually I'd use this way if I'm just trying to make my code look clean
]]

Second way:



local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(val1, val2)
if val2 then return end -- if the player is typing then we return to "end"

return print("--------------", "\n ".. val1.KeyCode)

end)

--[[
again to explain you can put anything into :Connect(function("RIGHT HERE") 
I'd just keep away from putting one of the Lua Global's in there example: "(continue) or (time) or (tick)"
]]

To close I’d like to give one last advice when :Connect(function(something).
The something you’re connecting to once it’s only mention in the function don’t expect that
you can use that variable outside of such function.

local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(val1, val2)
-- val1 and val2 can be used without a red line
end)

print(val1) -- but outside the function will give you a red line
-- expected output from print(val1) is : "error at line 7, unknown value"
1 Like

Simply, it just connects an RBXscriptsignal with a function.

When the signal is called, the function is fired with the demanded parameters.

and :Disconnect just disconnects the signal from the function, so the function won’t be triggered with the signal until it is re-connected.

2 Likes

This example is actually wrong. You’re calling printline with invalid arguments instead of just passing the function. Since print returns nothing, that line basically translates to:

UIS.InputBegan:Connect(nil)

You should do this instead:

local function printline(key)
    print("--------------\n"..key.KeyCode.Name)
end

local UIS = game:GetService("UserInputService")
UIS.InputBegan:Connect(printline)

OP:
Connect function (Event:Connect(func)) connects a function with the event. When the event (RBXScriptSignal) is fired, the function gets called with (or without) arguments. Every event has their own arguments.
You can also create your own events using BindableEvent's, but I’d honestly recommend using module scripts instead.

You may often see programmers using function() with Connect. Those functions are called “anonymous functions”, because they don’t have a name. They can be assigned to a variable, or passed to a function:

local square = function(n) return n^2; end;
local result = square(4);

-- they can also be called like this, but you should never do that
local result = (function(n) return n^2; end)(4);

The Connect function also returns a RBXScriptConnection, which allows you to disconnect the event from the function. You really should use it when you don’t need your function to be connected to the event anymore:

local part = workspace.Part;

local connection;
local function OnTouch(hit)
    print(hit.Name);
    connection:Disconnect();
end
connection = part.Touched:Connect(onTouch);

-- or

local connection;
connection = part.Touched:Connect(function(hit)
    print(hit.Name);
    connection:Disconnect();
end)

Also, the reason I am declaring a nil variable connection first and then assigning it, is to let the connected function use that variable too, otherwise it wouldn’t be available in its scope.

This is all that you should know about the Connect function. I hope I helped.

3 Likes

It doesn’t seem that people are explaining this so well, but these are called parameters.

Parameters are the variables / set of unpacked arrays (tables) that are given information in a function.

Now if you look at an API page, for EVENTS. It gives parameters.

This is because you can connect functions to events. This, is of course how you trigger and use functions. (With small exceptions)

Now you can send ANYTHING within the parmeters.

Take for example

local function Yes(Var1, Var2, Var3)
   print(Var1,Var2,Var3)
end

Yes(1,"pizza",workspace) --Output "1, pizza, workspace"
Yes("e","e","e") --Output "e,e,e"

Another important thing to know is ... This can be put in the function Parameters which holds the table of parameters sent.

Anywho, hope this informed you. :slight_smile:

2 Likes

I understand now what they are, but I still don’t understand what to put or the list of them. I looked at some developer page tutorials and they don’t show every one.

Is there like some sort of list for them somewhere that explains what they do? I know what they are used for but I need a list of them.

2 Likes

Hello.
When a function uses the ... parameter, it is called a “variadic function”, which means that the function accepts any number of parameters.
It is not a table, it’s actually a tuple. Let me demonstrate:

local function f(a, b, ...)
    local v1 = a; -- 4
    local v2 = b; -- 1
    local v3 = ...; -- "h"
    -- notice how v3 variable is set to the first value of the tuple, in this case "h"
    -- this is because a single variable can only hold 1 value at a time

    -- in order to retrieve all of the parameters back from the '...', we need to pack it into a table
    local vars = {...}; -- 'vars' now holds all of the values from `...` in an array
    return table.concat(vars); -- "hello"
end
f(4, 1, "h", "e", "l", "l", "o") -- *this is just an example, however in this case its recommended to use an array instead
1 Like

I’m not too advanced into that code, could you make it more clear? For example just naming it different things?

I don’t really know what table.concat means or vars.

I don’t really need to know about {…} yet.

You can find all of the events (and their parameters) in the object browser in the studio. Then, scroll down a bit until you find the event that you were searching for and you can view its description and parameters.

So…

Touched would be :Connect(function(Touched) ?

or ChildAdded would be :Connect(function(ChildAdded) ?

Don’t worry. At your stage, you don’t really have to use variadic functions as they’re not that useful than you might think. It’s better to use arrays as an alternative.

1 Like

Oh wait are the parameters on the left side?

No, you call Connect from the event. You receive parameters in function parentheses. I and others have provided some examples of how to use it in our previous posts. You can scroll up and look at them.

:sweat_smile: I dont know what arrays do either…

Sorry for still being dumbfounded but…

I couldnt find them as good examples because I wouldn’t know what var1 or var2 do. So far from my knowledge I can just go to the Objects tab and look at the function and look at the left tab for the parameters?

Functions are actually easy to understand if you KNOW how to understand them.

function test(arg1, arg2)
    print(arg1)
end

Arg1 and Arg2 are arguments passed through the function which would act the same as a variable- but eliminates a line.

When calling the function, you do need to pass the arguments, like this:

test(player.Name, hello) – That would pass the functions, player.Name being argument 1 and hello being argument 2.


So essentially, it’s just a variable created inside of the function, to reduce lines of code. (They can also only be accessed within the function body.)

Did you read all the posts that people have posted here?