Attempt to index nil with userId

I have this function when saving data, but for some reason player isn’t an index

local function saveData(player)
		
	local playerUserId = "Player_"..player.UserId

	local data = {
		Drinks = player.leaderstats.Drinks.Value;
	}

	local success, errormessage = pcall(function()
		myDataStore:SetAsync(playerUserId, data)
	end)

	if success then
		print("Data succefully saved!")
	else
		print("Data saving error")
		warn(errormessage)
	end

end
1 Like

This code should work if the parameter player is actually the player instance. Is there any errors you can give or more to your code?

The error in the title happens when you call local playerUserId = "Player_"..player.UserId but player is nil. You should check if player exists before continuing on with the function. Something to note, however, is that if player is nil it might mean you have an error somewhere else in your code.

1 Like

That is not how you call player. You do it by this: local playerUserId = player.UserId. However, I believe you have "Player_" for a reason, so hmm…

Let me know if you have the “Player_” for a reason and why.

Also, is it a local script or server script? @IMasterd

You might not be “sending” the player object when the players leaves.

You should do

game.Players.PlayerRemoving:connect(saveData) right?
Are you doing that, and are you ONLY calling this when the player is leaving?
Another thing, is that, do you have a wait before actually calling this function?

The wrong way to do this would be:

game.Players.PlayerRemoving:Connect(function(plr)
saveData(plr)
end)

Again, what could be happening, and is probably the issue is that, PLAYER got removed before the function could load. So now the PLAYER variable is NIL. since it’s not there anymore. And it seems like the problem is not on this part of the script, but somewhere else, if you agree, you should be sending the part of the script where you call this function.

This really isn’t the issue, the player object, it’s NIL. So it’s probably a problem, in another part of the script

Its not a local script its a server script. And I figured it out. Thanks for the feedback guys

2 Likes

hey, I recommend that you post what you did so others in the future can know. Just some advice.

3 Likes