Is it better to use functions then connect them, or just include the function in the event

I have seen lot’s of people use this as how they script event functions

Part.Touched:Connect(function(hit)

another common thing for event functions is this

 local function onTouched(Obj)
	stuff here
end

script.Parent.Touched:Connect(onTouched)

(I am using a touched event as an example)

Which one is better to script like?

1 Like

The 1st one is better in my opinion as its much easier to script

2 Likes

It doesn’t matter.

For short (<10 line) functions, I will usually use the second form. For longer things, I will separate them so it’s easier to read and modify in the future.

2 Likes

If the code is only used in one place, it doesn’t matter. Often times, a developer will use a named function in order to call it from more than one context, e.g. both an event handler, and something that can be explicitly called, which you can’t do with an anonymous function. An example such as you might have in a LocalScript waiting for the LocalPlayer’s character:

local function OnCharacterAdded(char)
    -- your chracter added code
end

player.CharacterAdded:Connect(OnCharacterAdded) -- Handles all future character spawns
if player.Character then
    OnCharacterAdded(player.Character) -- Direct call to handle already-spawned character
end

This way, you don’t have to copy-paste the block of code, and then possibly have a bug from changing one copy of the code and forgetting the other.

3 Likes