Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why do i get a nil in return if the variable is global?

I get an error about lol being nil, at line "print(lol)", i think im not understanding the flow of code that includes the player added and removed functions. Also the script can't be local.

Players = game:GetService("Players")

game.Players.PlayerAdded:connect(function(player)

lol = 3

end)

game.Players.PlayerRemoving:connect(function(player)

print(lol)

end)

2 comments

0

It's null because its only global in your scope { }. If you want it to be global throughout your script then place it outside of that function.

0

it's nullified because you already ended the script right there when you put an "end)"

1 answer

✓ Accepted answer

I think this will help your problem:

local lol = "EmptyString"
Players = game:GetService("Players") --This could also be 'game.Players'

game.Players.PlayerAdded:connect(function(player)
	lol = "3"
end)

game.Players.PlayerRemoving:connect(function(player)
	print(lol)
end)

Perhaps even thou you didn't make the 'lol' variable local in the PlayerAdded function, it probably still made usable only within that function.

Click here for info

The only difference between local functions/variables and global functions/variables is that a global functions/variable can be referenced before it is assigned, so this is correct:

local lol = "lol"
print(lol)

This is correct too:

print(lol)
lol = "lol"

but this is not:

print(lol)
local lol = "lol"

So yeah, hope this fixes your problem :D

if this answer helped you then
	Accept this answer ("Accept" button)
else
	Comment what was wrong and I'll fix it
end

This discussion is preserved as it was. New answers, comments, and votes are closed.