Can i disconnect called function?

Can i disconnect function like this and if not how do I can do that?

   local function foo ()
         print("Hello world");
   end
   foo();
   Disconnect(foo());

Should be explained here, if you haven’t already read it.

There is no need to disconnect the function anyways. You can just nil the reference instead:
foo = nil

1 Like

The way you have used ‘Disconnect()’ is wrong. To be able to use :Disconnect(), you need to use :Connect() on an event of some kind. In our example, we’ll run the ‘foo()’ function upon a player being added (there’s many events that exist, certain instances have certain events bound to them, such as the ‘Players’ service providing a ‘PlayerAdded’ event or a Humanoid object providing a ‘Died’ event to use).

To start, we’ll define our local function at the top of the script like so:

local function foo()
    print("Hello world");
end

We have our function, but we need to call it by using :Connect() on the PlayerAdded event for this example. The way we do this is like so:

local function foo()
    print("Hello world");
end

game:GetService("Players").PlayerAdded:Connect()

:Connect() takes one parameter being a ‘function’, right now in our code here, we’ve used :Connect() on an event but we haven’t actually provided any functionality to run when the PlayerAdded event is triggered. Since we want ‘foo()’ to run upon this happening, we can just provide that function as the parameter like so:

local function foo()
    print("Hello world");
end

game:GetService("Players").PlayerAdded:Connect(foo)

This will now run the ‘foo’ function when a ‘Player’ object is added into the game.

From this point, we can now think about utilising :Disconnect() which allows to disconnect/destroy a connection to a specified event. In our example, I will disconnect ‘foo’ from the PlayerAdded event as soon as the first player joins, I’m going to do this by using a simple bool to determine when the first player is added, also assigning our connection into a variable so we can use :Disconnect() to begin with like so:

local playerAddedConnection
local function foo()
    print("Hello world")
    playerAddedConnection:Disconnect()
    print("Event disconnected!")
end

playerAddedConnection = game:GetService("Players").PlayerAdded:Connect(foo)

If you have any questions you need answering, just ask. :grin:

3 Likes