My question is basically whether I should do this:
local function foo()
end
Event:Connect(foo)
Or this
Event:Connect(function()
end)
What are the pros and cons of both ways? One pro I can think of for the first way is that since the function is stored in memory I can now reuse that function later if I ever need to, one pro I can think of for the second way is it’s shorter (and maybe it’s taking up less memory because it’s not using a variable?).
If you’re calling them at different places in the code, that’s another obvious situation where you’ll want to reuse. In this case not to save memory, but to keep your code maintainable.
There’s actually a case where you can’t reuse the same function. Sometimes you need a closure for every occurence of the function call, e.g. to save different states per function call. An example would be an iterator factory. Check out Programming in Lua : 7.1, it’s super interesting stuff.
There are no specific performance advantages, but there’s a technical advantage if you’re using them correctly! The one function is declared while the other is anonymous. That means you can run the same function again if it was declared without the event, in case you need the function to be run elsewhere.
There are some instances where you want the function to be hooked to several listeners and that’s where you need to declare the function in the first place. Otherwise, an anonymous function would do. However, beware that connections are the culprits for memory leak if you don’t manage them correctly!