Can you get a returned value from the connection?

So i have a problem, look at that code

Players.PlayerAdded:Connect(function(Player)

Player.leaderstats.ChildAdded:Connect(function(object)
object.Value = "value"
return
end)

end)

so there is a connection inside a connection, and the thing is when a return in this example works, it stops this second connection, and not the first one, and i need it to stop that first one.

i thought that it would be easy to solve if this return returned some value to the first connection and made it run code that will stop it, but how do you get a returned value from a connection pls help me?

1 Like

You can’t stop connections, that’s just not really a thing.

Every time an event fires, each connection fires it’s listener function. Each of those function calls are then processed individually.

If you want to get a value out of the scope of a function, like the innermost function in your example code, you can just set a variable from the surrounding scope to a value. E.g.

Players.PlayerAdded:Connect(function(Player)
local leaderstatsChild

Player.leaderstats.ChildAdded:Connect(function(object)
object.Value = "value"
leaderstatsChild = object
end)

end)

If you want to wait until that value has been set and only continue processing the outer function when that happens, you will have to use one of many possible ways. You could use a loop that repeatedly checks if it’s been set, or you could use the :Wait method instead of :Connect in the specific cases where that works:

Players.PlayerAdded:Connect(function(Player)
local leaderstatsChild

Player.leaderstats.ChildAdded:Connect(function(object)
object.Value = "value"
leaderstatsChild = object
end)

repeat wait() until leaderstatsChild
end)
Players.PlayerAdded:Connect(function(Player)
    local leaderstatsChild = Player.leaderstats.ChildAdded:Wait() --it's not possible to do any processing to only continue if the *correct* child as been added.
end)

You could do some trickery like this:

Players.PlayerAdded:Connect(function(Player)
    
    local leaderstatsChild
    local waitForEvent = Instance.new("BindableEvent")
    
    
Player.leaderstats.ChildAdded:Connect(function(object)
object.Value = "value"
leaderstatsChild = object
waitForEvent:Fire()
end)

    waitForEvent.Event:Wait()
end)

A general solution for this kind of problem is to use promises. Look those up if you’re interested, there’s plenty of information here on the devforums.

1 Like

yeah ik about events thanks but i still think there is a better way cause you can prevent a connection from continuing like that:

Connect(function()
if hit.Parent.Name = “ThanksRoBama” then
return
–and it wont run further
end
hit.Parent:DEATH()
end)

so yeah idk