Simple question on functions

Lets say I make this function here

v.MouseButton1Click:Connect(function()
         print("Click")
end)

Its not about the whether this script works the REAL question to be asked is If I make this function again – like so

v.MouseButton1Click:Connect(function()
         print("Click")
end)

Does it have this function twice and does that take up memory?, is it bad practice to redefine this function?, Would I have to Disconnect() the function to make a new one?

You don’t have to disconnect a connection to make a new one. If you do run that code twice then you’ll spawn up two connections which both consume memory, yes. They will both be functionally similar and both get fired on click but are not exactly the same. Since you’re using lambdas, that’s two different functions in memory and two different connections in memory.

If at all possible you should avoid using a lambda with a connection that you intend to write multiple times unless you know it’ll get cleaned up at some point (ancestor is destroyed or connection is explicitly disconnected) or unless it’s appropriate to do so. Write the function once then have an implementation that creates a new connection with that function (like with CollectionService).

3 Likes

By the way, if the function is connected to MouseButton1Click, How would I disconnect it as it does not have a name.

You can store a RBXScriptSignal with a variable to disconnect it whenever you want.

local connection

connection = v.MouseButton1Click:Connect(function()
	print("Click")
end)

connection:Disconnect()
1 Like