Declaring Function Before Event?

While I was working with another scripter friend of mine, I was pointed out that I should declare the function that the event should run before the connect function is called. Here is what I mean:

local function PlayerAddedFunction(Player)
    -- do whatever you need to do here
end

for _, Player in pairs(game.Players:GetChildren()) do
    PlayerAddedFunction(Player)
end

game.Players.PlayerAdded:Connect(PlayerAddedFunction)

Is there a difference between that and just this?

game.Players.PlayerAdded:Connect(function(Player)
    -- do whatever you need to do here
end)

Does the former have more efficiency, less memory usage, something that I’m missing as compared to the latter? Is it just personal preference?

Any help will be appreciated, thanks in advance.

Both pieces of code will give the same result (if we ignore that one for-loop in the first example). Upside of the first example is that the PlayerAddedFunction function can be reused elsewhere in the code as it is defined independently. Upside of the second example is that the event and function are kept together, which makes the code more readable in my opinion as you don’t split the logic across different sections of the script: If you see the event, you also immediately see the logic linked to that event.

Speed, memory and other factors don’t play any significant role in the code you provided. The difference between the two is neglectible, so it all comes down to what practice is better in terms of readability and usability.

Also quick note, in the first example you call PlayerAddedFunction within the Connect method. You should remove the two brackets to prevent an error.

2 Likes

In OP’s case the first option should be used because he is calling the same code in multiple different places so play solo tests work. This is probably why he was told to do it like that and may be confused about the difference between anonymous and declared functions when the real difference is he is now scanning for existing players.

2 Likes