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

Why do some people do :Connect(function_name)?

Asked by 4 years ago
Edited 4 years ago

Why do some people :Connect(functionname) Example:

function OnTouch(hit)
    print(hit.Name.." has touched it")
end

game.Workspace.Part.Touched:Connect(OnTouch)

I use :Connect(function() which I feel is a bit better

Example:

game.Workspace.Part.Touched:Connect(function(hit)
    print(hit.Name.." has touched it")
end)

Is there any different or is this just a big debate on the coding community?

2 answers

Log in to vote
0
Answered by 4 years ago

Using :Connect(function() is what we call an anonymous function. Anonymous functions run code as functions would but they cannot be called. When you use :Connect(Function_Name), you are pretty much doing the same thing as an anonymous function, but you are calling a specific, normal function when the event is triggered. As you can see in the anonymous function we create a function itself inside of the :Connect(). I suppose that it is entirely down to preference as others have stated, however sometimes I find myself using the latter method to reuse a function for other purposes rather than being fired upon an event being triggered. If your code you are running is specifically event triggered, perhaps using an anonymous function would be more elegant - but using a non anonymous function always looks a little neater.

Ad
Log in to vote
0
Answered by 4 years ago

Honestly I don't think there's a difference but to some people, they think the code looks a little cleaner and easier to understand. Or maybe they're going to use the function multiple times

0
But like some people do simple functions like the one I showed as an example, like the first example. Even the Roblox Developer Resources do it like the first one. I normally do the second one, if I need to call a function, I call the function inside the function (example 2) BradNewTypical 232 — 4y
0
I think it's just a matter of preference. I don't really think it makes a difference in performance nor behavior cucucu0001 35 — 4y

Answer this question