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

How to save leaderboard stats with DataStore?

How can I save my leaderboard Data with DataStore? Leaderboard script:

local function onPlayerJoin(player)
   	local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player
   	
	local Wins = Instance.new("IntValue")
	local Wval = game.ReplicatedStorage.leaderstats.Wins.Value
    Wins.Name = "Wins"
    Wins.Value = Wval
    Wins.Parent = leaderstats
	
	local Coins = Instance.new("IntValue")
	Coins.Value = 50
	local Cval = game.ReplicatedStorage.leaderstats.Coins.Value
    Coins.Name = "Coins"
    Coins.Value = Cval
    Coins.Parent = leaderstats
	
	while true do
		wait(60)
		Coins.Value = Coins.Value +10
		print("10 minutely coins were awarded!")
	end
end

game.Players.PlayerAdded:Connect(onPlayerJoin)

1 answer

First, you will need to create a DataStore. Define the DataStoreService first by putting:

local datastore = game:GetService("DataStoreService")

Then to create your DataStore(s) you do this:

local coins = datastore:GetDataStore()

Datastores store values under a key, a key is inside of the DataStore you provided and stores the values inside it. Keys always should be unique, so data can't be lost or overwritten easily. To save data under a key you do this:

coins:SetAsync(your unique key goes here, then your value in this argument)

To recieve data, you do this:

local plrcoins = coins:GetAsync(unique key)

So, when you use the variable plrcoins the variable will equal the data stored under that key.

It's good to know that DataStores do error from time to time. So when they do, you do not want them breaking your whole leaderboard script. So whats the soloution? Wrap the DataStore functions in a pcall. Like this:

local success, error = pcall(function()
     coins:SetAsync(key,valuetosave)
end)

if success then
 print("Success!")
 else
  print(error)
end

The "success" variable provided is the first thing a pcall will return. If it ran, it returns true, If it had an error, it returns false and the returns the error under the error variable.

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