Not sure why this prints nil

I have no idea how this prints nil

ProfileChanged.OnClientEvent:Connect(function(data)
	print(data) -- prints correct data sent from ServerScript
	 userdata = data -- global variable 
	print(userdata) -- prints correct data
end)
print(userdata) -- prints nil

can provide more info if needed

It probably prints nil because it is outside the function, inside the function userdata is changed and it prints what it has changed too however since that other print statement is set outside the function it only executes when the script is first run and Iā€™m assuming userdata is initialized to nil, hence it would print nil when the script is loaded.

2 Likes

The event runs when the event happens, and the rest of the script continues until then. If you want to wait for the remote event, do this.
local userdata = ProfileChanged.OnClientEvent:Wait()

1 Like