How to returrn a value inside a connect function which i want to disconnect at the same time

how would i return a value inside a connect function that i would like to disconnect at the same time for example

local added

added = game.Players.PlayerAdded:Connect(function(player)
    
    added:Disconnect()
    return player
    
end)

print(added)

this just prints prints connection but i want it to print the value i am returning instead(player) ive tried two variables but the second one just prints nil instead

Need to assign the player to an upvalue. Return in a function given to a Connect method means that the value would be returned to the Connect method call and the engine doesn’t do anything with any values returned to Connect.

local added, player

added = Thing:Connect(function (foobar)
    player = foobar
    added:Disconnect()
end)

I mean though, unless you’re doing anything else in this function, you just check whatever gets passed to PlayerAdded and then disconnect, so why not just use wait?

local player = Players.PlayerAdded:Wait()

Functionally the same and doesn’t require you to manage a connection. When PlayerAdded fires, this will return whatever PlayerAdded fired with.

4 Likes

pog ty reason im not using is wait because what i showed in the question was just a example of my question im actually just using it for other stuff

1 Like

I’m not sure how heavy you lean towards functional programming but upvalues/non-locals can be avoided.

Providing everything is contained within functions you can simply pass that player instance from its “.PlayerAdded” event to any function which requires it.