Connect local functions vs connecting unnamed functions

My apologies for the poorly worded title.

I am asking about the perks and disadvantages of two cases: using local functions and connect them or connecting unnamed functions. I wish to improve my practices when developing.

Take these two for example. Note these are NOT in a module script:

local function yes()
    print("yes")
end

part.Touched:Connect(yes)
part.Touched:Connect(function()
    print("yes")
end)

I am asking which of these two cases is both more efficient and more useful.

2 Likes

With the former it is useful for if you want to connect multiple events to the same function.

part.Touched:Connect(yes)
part.TouchEnded:Connect(yes)
-- etc

Functions are meant to be containers of reusable code, and that is what you are doing; reusing the code.

Also if you have multiple parts you might wanna connect the same function.

for _, part in ipairs(parts) do -- parts might be a table of parts
    part.Touched:Connect(yes)
end

For the latter, you likely won’t be reusing the code, hence using a literal function is fine.

Btw Lua has no concept of “local functions”; all functions have no name

4 Likes

The advantage of holding reference to an RBXScriptConnection is that once you assign the event connection a variable, you can call connection:Disconnect() to prevent memory leaks in cases where you’re sure it’s going to be a significant amount of time before the connection is needed again.

When you use anonymous functions, such as

  Part.Touched:Connect(function(t) 

  end)

You lose your reference not assigning it a variable, though through possibly hacky means you could still forge the connection back, it’s still better to not use an anonymous function when you need to disconnect.

1 Like