Why wont this variable set if I returned it?

Hey Devforum,

Why won’t this work I have been curious about this forever? I usually just find a workaround but I just wanted to ask this time.

local player
game.Players.PlayerAdded:Connect(function(p)
	player = p
	print(player.Name)
	return player
end)

p does equal the player object but outside of the function player is still nil. How so if I returned it?

What are you trying to achieve? There is probably an easier way than the method you’re going down right now

return player does nothing. all you need to do is player = p

local player
game.Players.PlayerAdded:Connect(function(p)
    player = p
    print(player.Name)
end)

Simply set a variable outside of the scope wait for the player to be added pass in the newly added player. Assign the variable to the passed in player variable then return the variable to the scope so it can be used outside of the function.

No, that wouldn’t work player would still be nil. Here’s a better example of what I’m trying to do;

local player
game.Players.PlayerAdded:Connect(function(p)
	player = p
end)
print(player.Name)

if I print player.Name it will be nil because player is nil.

Where did you put this, in a local script?

Server script I need the player object outside of the scope of the function.

It’s probably because game.Players.PlayerAdded is basically a coroutine and doesn’t delay any other part of the code try adding this.

repeat wait() until player ~= nil

would look like this

local player
game.Players.PlayerAdded:Connect(function(p)
    player = p
end)
repeat wait() until player ~= nil
print(player.Name)

Thanks so much I appreciate it.

Another solution is using Event:Wait()(basically waiting until the event fires):

local Player = game.Players.PlayerAdded:Wait()
print(Player)

Your code breaks for more than 1 player though, because the variable gets overridden.

Your right thanks for pointing this out I’m switching it to client script.

1 Like

You can use a server script, just not in the method above. Index the names into a table and reference them through there.

Ex:

--Server Script

--Table to keep them in
local playersInGame = {}

--Insert to table when they join the game
local function onPlayerAdded(player)
	playersInGame[player.Name] = player
end

--Remove from table when they leave the game
local function onPlayerRemoved(player)
	playersInGame[player.Name] = nil --gets garbage collected
end

Players.PlayerAdded:Connect(onPlayerAdded)
Players.PlayerRemoving:Connect(onPlayerRemoved)