I want to know why people Connect to Events like this, I couldn’t find anything on it, and nobody really mentions it, so I thought I’d make a post asking why.
Example
function touched(hit)
print(hit.Name)
end
script.Parent.Touched:Connect(touched)
This is the default way of connecting events and is seen throught roblox-wiki styled code. It simply runs the function when the event is fired. The main advantage of using this over simply
Event:Connect(function()
end)
Is you can connect multiple events to the same function
What you see in this example is basically the same as what you have in your example, the exception being instead of creating a new function solely for this connection, that we use a preset in your example instead. In the example I’ve listed, we’re just tying a new function instead of an already created function, this is fairly common, both methods are practical.
It allows for re-usability. Say you have multiple buttons that you want to change a textLabel with. Instead of writing 5 different functions that do the same thing for 5 buttons, you can write one function with similar functionality and pass in a different parameter for each button.
Some might say it can be a bit cleaner to connect it to a function. Since when you create a script structure it looks a bit cleaner like this. This makes it a bit more easier to see the events a script is using
local door = workspace.Door
local connection
local ActivateOpen = Instance.new("BindableEvent")
ActivateOpen.Parent = script
local function CloseDoor()
connection:Disconnect()
print("Door closing...")
task.wait(1)
ActivateOpen:Fire()
end
local function OpenDoor()
connection:Disconnect()
print("Door opening...")
task.wait(1)
connection = door.Touched:Connect(CloseDoor)
end
local function OnActivateOpenEvent()
connection = door.Touched:Connect(OpenDoor)
end
ActivateOpen.Event:Connect(OnActivateOpenEvent)
--initial setup
connection = door.Touched:Connect(OpenDoor)
This may seem convoluted, but it will prevent multiple function executions running. Adding debounce or checks will never be that efficient.
Edit:
There are however some benefits to using inline function declaration. For example:
for _, part in pairs(SomeFolder:GetChildren()) do
part.Touched:Connect(function(hit)
print(part.Name .. " has been hit. We would not be able to figure out that easily by using a named function")
end)
end
Notice how you still have access to the part that you are connecting the function. True, it can be done without this trick, but not as easy as this.