Using functions for :Connect()

Is there really a difference between doing this:

local function onInputBegan(input, gameProcessedEvent)

end


UserInputService.InputBegan:Connect(onInputBegan)

vs this?

UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)

end)

There is virtually no difference but it might help to understand what you’re actually doing.

The top one is naming a function and assigning it to an event connection. The bottom one is using an “anonymous function” (meaning a function with no name) which will no longer be referenceable when the connection disappears/disconnects.

1 Like

which one do you suggest is better for keeping your code clean/organized for long scripts or just keeping your code clean in general?

For me, I see the top one as being more readable because there’s a name that tells me what is being done in the function.

However, there’s nothing wrong with the bottom option and sometimes it is better in other cases. I don’t necessarily choose to use one over the other.

1 Like

There are different use cases for the two. the connection on the top is normally used for better readability and reusability meaning you can call it again for different events and (etc.). The one on the top also can be disconnected if no longer needed. You should only nest the function in the connection(the bottom example) if you are only going to use that function for that certain event and if you aren’t going to disconnect it.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.