How can i change this datastore script to save 2 values?

Hello, i was playtesting my game and realised that my value of “Upgrades” would be the same as the value of “Points” when i rejoined. The problem is i dont know how to change my script to make it work. Here is the script:

local datastoreservice = game:GetService("DataStoreService")
local datastorage = datastoreservice:GetDataStore("datastorage")
print("Variables loaded")

local currentSession = {}

local function Load(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local Points = Instance.new("IntValue")
	Points.Name = "Points"
	Points.Parent = leaderstats
	
	local Upgrades = Instance.new("IntValue")
	Upgrades.Name = "Upgrades"
	Upgrades.Parent = player
	
	print("Leaderstats created")
	
	local data
	local success, errormessage = pcall(function()
		data = datastorage:GetAsync(player.UserId)
	end)
	print("Data load happened")
	
	if success then 
		print("Data loaded") 
		if data then
			player.leaderstats.Points.Value = data
			player.Upgrades.Value = data
			print(Points.Value)
			print(Upgrades.Value)
		else
			player.leaderstats.Points.Value = 0
			player.Upgrades.Value = 0	
		end
	else
		warn("Error happened while loading data: "..errormessage)
	end
end

local function Save(player)
	local success, errormessage = pcall(function()
		datastorage:SetAsync(player.UserId, player.leaderstats.Points.Value) 
		datastorage:SetAsync(player.UserId, player.leaderstats.Upgrades.Value)
	end)    
	
	if success then
		print("Data saved")
	else
		warn("Error happened while saving data: "..errormessage)
	end     
end

game.Players.PlayerAdded:Connect(Load)
game.Players.PlayerRemoving:Connect(Save)
game:BindToClose(function()
	for i,v in pairs(game.Players:GetChildren()) do
		Save(v)
	end
end)

The problem is the:

if data then
	player.leaderstats.Points.Value = data
	player.Upgrades.Value = data
	print(Points.Value)
	print(Upgrades.Value)
else

It basically replaced the upgrades value with the points value allowing people
to boost their income significantly. Also, i have both game.Players.PlayerRemoving and game:BindToClose incase one doesnt work.

To clarify, im trying to add another “data” that saves the Upgrades value but i dont know how.

try making a table to save like this:

local stats = {
["Points"] = player.leaderstats.Points.Value,
["Upgrades"] = player.Upgrades.Value
}
datastorage:SetAsync(player.UserId, stats)

You can get the table and data by doing this:

local stats = datastorage:GetAsync(player.UserId) or {}

points.Value = stats.Points
upgrade.Value = stats.Upgrades
2 Likes

im probably doing something wrong because this doesnt seem to work