How can I improve my basic datastore?

Right now my code all it does is just saves the leaderstats and I want to save a table of parts instead of intvalues, is that possible?

I have considered using updateAsync since I heard thats better

--Services 
local dss = game:GetService("DataStoreService")
local Players = game:GetService("Players")
--Variables 
local leaderboardDS = dss:GetDataStore("LeaderboardDS")

--Functions 
local function leaderstats(player)
	local folder = Instance.new("Folder")
	folder.Name = "leaderstats"
	folder.Parent = player 
	
	local Cash = Instance.new("IntValue")
	Cash.Name = "Cash"
	Cash.Parent = folder 
	
	local XP = Instance.new("IntValue")
	XP.Name = "XP"
	XP.Parent = folder 
end

local function loadData(player)
	leaderstats(player)
	local UserId = player.UserId 
	
	local data 
	local success,err = pcall(function()
		data = leaderboardDS:GetAsync(UserId)
	end)
	
	if success then 
		player.leaderstats.Cash.Value = data[1]
		player.leaderstats.XP.Value = data[2]
	end
end

local function saveData(player)
	print("player Left")
	local UserId = player.UserId 
	local leaderstats = player.leaderstats 
	local CASH = leaderstats.Cash.Value 
	local XP = leaderstats.XP.Value 
	
	
	local data = {CASH, XP}
	
	local success, err = pcall(function()
		leaderboardDS:SetAsync(UserId, data)
	end)
	if success then 
		print("data loaded successfully")
	end
	if not success then 
		if err then 
			warn("data not saved")
		end
	end
end

--Events 

Players.PlayerAdded:Connect(loadData)
Players.PlayerRemoving:Connect(saveData)
1 Like

It looks great! Do the leader stats show up and save? The code looks good but I am a noob with data stores so I don’t know for sure.

1 Like

Definitely use UpdateAsync().

3 Likes

Overall looks good, I have just two additions to make:

1). You can return in the pcall instead of using another variable and assigning to it, err will instead be the data if it succeeds.

For example:

local Success, Response = pcall(function()
    return leaderboardDS:GetAsync(UserId);
end)

if (Success) then
    --// Response is now data
end

2). Ensure that you handle when it fails, perhaps by retrying until it succeeds.

2 Likes
  1. You do not have to check if err exists. If your success variable is false, err will always exist. This section of mistake can be found within saveData.
  2. Consider UpdateAsync if you ever need to worry about the last save. SetAsync works fine in your case though.
2 Likes