"attempt to index nil with number" & "attempt to index nil with 'UserId'" when using datastore

I am creating a datastore for a game i’m working on and have decided to create the datastore differently to how I usually would to include pcall to make it more secure. I have errors with “attempt to index nil with number” & “attempt to index nil with ‘UserId’” and im unsure on how to fix these having never really used pcall before.

Ive attached a screenshot of the errors and my datastore script in full. Any help appreicated!

local DSS = game:GetService("DataStoreService")
local DS = DSS:GetDataStore("RadarData")
local Players = game:GetService("Players")

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

	local Currency = Instance.new("IntValue",leaderstats)
	Currency.Name = "RadarTokens"
	Currency.Value = 0
	
	local Exp = Instance.new("IntValue",leaderstats)
	Exp.Name = "ATCExp"
	Exp.Value = 0
	
	local data
	local success, errormessage = pcall(function()
		data = DS:GetAsync(player.UserId)
	end)
	
	if success then
		player.PlayerData.RadarTokens.Value = data[1]
		player.PlayerData.ATCExp.Value = data[2]
	else
		error("Error gathering user data. Please report in our comms server. " .. errormessage)
	end
end)

Players.PlayerRemoving:Connect(function(player)
	local success, errormessage = pcall(function(player)
		DS:SetAsync(player.UserId, {player.PlayerData.RadarTokens.Value, player.PlayerData.ATCExp.Value})
	end)
	
	if success then
		print("Player data saved successfully.")
	else
		error("There was an error saving user data. " .. errormessage)
	end
end)
1 Like

You are initializing data with nil, but data = DS:GetAsync(player.UserId) can also return nil if there is no saved data found under that key (which is most common). So, after getting the data, you are assuming its a table and trying to access index 1.

This parameter isnt needed as it overwrites the valid parameter as nil


hope this makes sense

1 Like

Thanks, that has removed the error on saving. Could you tell me what you think would be best to get around erroring when a user doesn’t have any data under their key?

Every user that joins your game should be initialized with default data. Next, overwrite the default data with any saved data. If they don’t have any saved data, they are left entirely with the default data.
You are already doing this when you create the player data folder, you are just assuming they have data. A simple fix would just be an if-statement.

if success then
	if data then
		-- overwrite the default data
		player.PlayerData.RadarTokens.Value = data[1]
		player.PlayerData.ATCExp.Value = data[2]
	end
else
	error("Error gathering user data. Please report in our comms server. " .. errormessage)
end

Cheers, thats way more simple than the way I would of done it. Thanks for the help :smiley:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.