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

Why does my leaderboard datastore not work?

I created a script that stores a players wins when they leave the game, and gets their wins when they join, but it always errors.

datastore = game:GetService("DataStoreService")
WV = datastore:GetDataStore("WinsValue")
game.Players.PlayerAdded:Connect(function(player)
	local folder = Instance.new("Folder")
	folder.Parent = player
	folder.Name = "leaderstats"
	local wins = Instance.new("IntValue")
	wins.Parent = folder
	wins.Name = "Wins"
	----------------------------
	local winsvalue 
	local suc,err = pcall(function()
		winsvalue = WV:GetAsync(player.UserId) 
	end)
	if suc then
		wins.Value = winsvalue
	else
		print("There was an error while trying to get data")
	end
end)
--------------------------------------------------------------------------------------------------------------------------------------------------------
game.Players.PlayerRemoving:Connect(function(player) 
	local suc,err = pcall(function()
		WV:SetAsync(player.UserId,player.leaderstats.Wins.Value)
	end)
	if suc then
		print("Successfully stored data")
	end
	if err then
		print("There was an error while trying to store data")
	end
end)

2 answers

✓ Accepted answer

I found out that my datastore was fine, the problem was that in anotehr script I had the wins were updated on the client, where they should be updated on the server.

The value when joining needs to be set to a table in order within the DataStore. The value when leaving needs to be set as an array. Lastly, in the if suc, else statement, don't just print, Run the GetAsync.

datastore = game:GetService("DataStoreService")
WV = datastore:GetDataStore("WinsValue")
game.Players.PlayerAdded:Connect(function(player)
    local folder = Instance.new("Folder")
    folder.Parent = player
    folder.Name = "leaderstats"
    local wins = Instance.new("IntValue")
    wins.Parent = folder
    wins.Name = "Wins"
    ----------------------------
    local winsvalue 
    local suc,err = pcall(function()
        winsvalue = WV:GetAsync(player.UserId) 
    end)
    if suc then
        wins.Value = winsvalue[1]
    else
	local toSave = {wins.Value}
        print("There was an error while trying to get data")
    end
end)
--------------------------------------------------------------------------------------------------------------------------------------------------------
game.Players.PlayerRemoving:Connect(function(player) 
    local suc, err = pcall(function()
        WV:SetAsync(player.UserId, {player.leaderstats.Wins.Value})
    end)
    if suc then
        print("Successfully stored data")
    end
    if err then
        print("There was an error while trying to store data")
    end
end)

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