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

[ANSWERED] How to fix "attempted to index local 'player' (a nil value)"?

I am making a leaderstats script with DataStores, and whenever I leave the game, the script throws an error, "attempted to index local 'player' (a nil value)". I have seen the forum posts throughout scripting helpers and other websites detailing how to fix this. I have tried these, and they work, but the players' data needs to save for the next time they join. We need the player to not be a nil value to save the data. How to fix? Thanks in advance! :D

The error occurs at line 32, and is later thrown to the console by line 39.

Code:

local DataStore = game:GetService("DataStoreService")
local ds = DataStore:GetDataStore("PointsData")

print("started")

game.Players.PlayerAdded:Connect(function(player)
 local leaderstats = Instance.new("Folder", player)
 leaderstats.Name = "leaderstats"

 local points = Instance.new("IntValue",leaderstats)
 points.Name = "Points"

 local data
 local success, errormessage = pcall(function()
	data = ds:GetAsync(player.UserId.."-points")
end)
 
 if success then
	print("got data")
	points.Value = data
else
	print("could not get data")
	warn(errormessage)
end

end)


game.Players.PlayerRemoving:Connect(function(player)
 
	local success, errormessage = pcall(function(player)
		ds:SetAsync(player.UserId.."-points",player.leaderstats.Points.Value)
	end)
	
	if success then
		print("Points saved successfully.")
	else
		print("Error saving data.")
		warn(errormessage)
	end
	
end)

1 answer

✓ Accepted answer

My bad. I added a "player" variable to the pcall function on line 31. Thanks everyone!

1 comment

0

yay good job

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