Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

What is the advantage of using functions instead of just writing it under events?

What is the advantage of using this:

local function onPlayerAdded(player)
	print(player.Name)
end
game.Players.PlayerAdded:Connect(function(onPlayerAdded)

Instead of this:

game.Players.PlayerAdded:Connect(function(player)
	print(player.Name)
end)

It could also apply to this:

local function doWhileLoop()
	print("a")
end
while wait() do
	doWhileLoop()
end

Instead of this:

while wait() do
	print("a")
end

So basically, why should I consider using functions instead of just writing under the thread?

2 answers

✓ Accepted answer

Normally, I use

local function onPlayerAdded(player)
    print(player.Name)
end
game.Players.PlayerAdded:Connect(onPlayerAdded)

and

while wait() do
    print("a")
end

But, there's no exact reason, the only advantage I see by defining funciontions outside of the connect event is because you can re-use it, such as connecting 2 events to the same function.

It also makes your code a bit more organized


If this answers your question, please mark the answer as accepted

1 comment

0

Thanks for the explanation, I genuinely tought I was making my game laggier by not using functions, but looks like I'm fine.

The advantage is that you can connect one function to two different events Example:

local function OnLeaveRace(player)
	--some code here to remove player from the race
end
ServerDisqualifyEvent.Event:Connect(OnLeaveRace)
PlayerForfeitRaceEvent.OnServerEvent:Connect(OnLeaveRace)

Other times you may want to reuse the same function inside two different functions: Example:

local function UpdateMana(player, newAmount)
	--some code
end
PlayerCollectMana.Event:Connect(UpdateMana)

local function OtherFunction(player)
	--some code
	UpdateMana(player,20)
end

Hope this helps!

This discussion is preserved as it was. New answers, comments, and votes are closed.