Disconnecting functions directly

Is it possible to disconnect functions from events like this?

button.Activated:Connect(function()
	--code
	button.Activated:Disconnect()
end)


Instead of this

local a = button.Activated:Connect(function()
	--code
	a:Disconnect()
end)

The two functions of RBXScriptSignal are :Connect() and :Wait(). RBXScriptSignal is actually a part of the instance. What it returns is a RBXScriptConnection. You can then disconnect from this. So no, you cannot do what you show in the top portion.

When you do local-style declarations, the variables are declared after the right hand side is evaluated. Essentially, to get a within your connection, you need to pre-declare it.

local a = nil -- this declares `a` as a variable
a = button.Activated:Connect(function() -- this assigns to the local variable
    -- code
    a:Disconnect()
end)

Note that you can also just do local a without = nil, because it implicitly defines as nil.

2 Likes

Any specific reason as to why this is? Been wondering myself, how does this work, if the variable is declared after the rhs is evaluated why doesn’t it get nil, as an upvalue in the closure

Lua evaluates the values and then declares the variable. local a = function() end would treat a as a global inside the function. Variables are only seen by the scope when they are declared.

1 Like