Should I create functions beforehand and then connect them to events or create them as I'm connecting them events?

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?).

1 Like

You answered your own question. In cases where you need to reuse the listener there you go. Store a reference to the function in a variable.

If you don’t need to reuse it then go with the second approach

2 Likes

A lot of times I don’t know whether I’m going to want to reuse a function or not in the future. Hence why I said “if I ever need to.”

1 Like

Then just always create them beforehand if your’re unsure. The readibility for me is quite the same for both methods if your worried about that.

1 Like

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!