Help with DataStoreService

I am trying to make a saving leaderstats script (from scratch so I can learn better) however, I am running into some issues. I don’t want to just copy off someone or watch a tutorial as this is something that I will need to learn how to do this eventually since it is a necessity for almost every game! So that is why I am doing this from a blank script. Here is my script and a picture of my output.


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

game.Players.PlayerAdded:Connect(function(player)
	
	local Inventory = Instance.new("Folder")
	Inventory.Name = "Inventory"
	Inventory.Parent = player
	
	local SelectedKit = Instance.new("StringValue")
	SelectedKit.Name = "SelectedKit"
	SelectedKit.Parent = player

	local Coins = Instance.new("IntValue")
	Coins.Name = "Coins"
	Coins.Parent = player
	
	local data, result = pcall(function()
		 LeaderstatsDataStore:GetAsync("Stats-"..player.UserId)
	end)
	
	if data then
		Kudos.Value = data.Values.Kudos
		SelectedKit.Value = data.Values.SelectedKit
	else
		warn(result)
	end
	
end)

game.Players.PlayerRemoving:Connect(function(player)
	local LeaderstatsSavingData = {
		Values = {
			["Coins"] = player.Coins.Value;
			["SelectedKit"] = player.SelectedKit.Value;
		}
	}
	
	local success, result = pcall(function()
		return LeaderstatsDataStore:SetAsync("Stats-"..player.UserId,LeaderstatsSavingData)
	end)
	
	if success then
		if result then
			print(result)
		end
	else
		warn(result)
	end
end)

Here, the variable “data” is true if the the datastore gets something and false is the datastore does not. Try using result.Values instead.

So if there is data (which there is as it is true), then how could I retrieve the data. Would I use :ReadAsync()?

the data is actually the second variable “result” you use GetAsync as normal.
we usually call the first variable “Success” check roblox studio docs for more

1 Like

Mark this as solution

	local success, result = pcall(function()
		 LeaderstatsDataStore:GetAsync("Stats-"..player.UserId)
	end)
	
	if success == true then -- if the pcall function above was successful in retrieving data. "if success then" also works.
		Kudos.Value = result.Values.Kudos
		SelectedKit.Value = result.Values.SelectedKit
	else
		warn(result) -- i would put what the stats would be on default here
	end

I also just realized. I used Coins and Kudos mixed up (they are 2 different types of currencies in my game). Sorry if I made it confusing!

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