Question about events

I have a simple question about events. What is the difference between these 2 methods of hooking up events? I will be using Touched as an example:

script.Parent.Touched:Connect(function(part)
	--do stuff
end)

and:

local function partTouched(part)
	--do stuff
end

script.Parent.Touched:Connect(partTouched)

As far as I know they both do the same thing, so when would I use one method over the other?

They’re both the same. :Connect() connects an event to a function to run your code when it fires. In the first method, you are connecting Touched to a new function, and then running the code inside.

In the second method, partTouched is already defined and you’re connecting Touched to it.

I think it’s really up to your preference which way you use it.

1 Like

Makes sense. I just don’t see any clear reason to use the second method especially since you can use less lines with the first method.

1 Like

You could use the second one if you want to make one function for multiple events, so for example

local function myEvent()
	-- do stuff
end

script.Parent.Event1.OnServerEvent:Connect(myEvent)
script.Parent.Event2.OnServerEvent:Connect(myEvent)
script.Parent.Event3.OnServerEvent:Connect(myEvent)
3 Likes

Ah, I didn’t think about this. That is potentially a good use