Data stores for new players

So how would you developers handle this situation, a new player joins and the data store retreives the players data, but the player has nil data so data store throws an error. Thats whats going on with me.

local DataStoreService = game:GetService("DataStoreService")
local PlayerDataStore = DataStoreService:GetDataStore("PlayerDataStore")

game.Players.PlayerRemoving:Connect(function(player)
	
	local pastData = PlayerDataStore:GetAsync(player.UserId)
	local pastKills = pastData[1]
	local pastWipeouts = pastData[2]
	local currentKills = player.leaderstats.kills.Value - pastKills
	local currentWipeouts = player.leaderstats.Wipeouts.Value - pastWipeouts
	local data = {currentKills, currentWipeouts}
	
	local success, err = pcall(function()
		PlayerDataStore:IncrementAsync(player.UserId, data)
	end)
	
	if err then
		
		return error("Cannot save data for " .. player.Name)
	end
end)

game.Players.PlayerAdded:Connect(function(player)
	local success = PlayerDataStore:GetAsync(player.UserId)
	
	if success[1] == nil then
		success[1] = 0
	end

	print(success[1]) -- its broken bc the new player has a nil table
	
	
	player.leaderstats.kills.Value = success[1]
	player.leaderstats.Wipeouts.Value = success[2]
end)

I just can seem to figure out how to make it so that the new players will not cause the data store to throw an error.

1 Like

Very easy! So, when you do β€œ:GetAsync(),” afterwards you should write or and then the default stat. For example, if I had a Total Kills data store (so simply saving a number), I would write:

local Kills = KillsData:GetAsync(player.UserId) or 0

This is because 0 would be the default value. Whenever the :GetAsync() returns nil, the script will simply set Kills equal to the value after β€œor.” I am assuming your data store is storing a Table which has 2 values, so what I ASSUME you would want to do is write " or {0,0} " after your :GetAsync(). Hope this helps.