Need help saving multiple values in one datastore

I wanna save 2 intvalue when the player left. I’ve tried this way on youtube and devforum but it still doesn’t save the values and I got no errors in the console too. Here is the “Saving points” code:

local DataStoreService = game:GetService("DataStoreService")
local playerPointsData = DataStoreService:GetDataStore("PlayerPoints")
local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local Kills = Instance.new("IntValue")
	Kills.Name = "Kills"
	Kills.Value = 0
	Kills.Parent = leaderstats
	
	local Deaths = Instance.new("IntValue")
	Deaths.Name = "Deaths"
	Deaths.Value = 0
	Deaths.Parent = leaderstats
	
	local data
	local success, errorMessage = pcall(function()
		data = playerPointsData:GetAsync("Player"..player.UserId)
	end)
	
	if success then
		print("Successfully get player's points")
		Kills.Value = data["Kills"]
		Deaths.Value = data["Deaths"]
	else
		warn(errorMessage)
	end
end)

local function getPlayerStatsValues(player)
	local playerStats = {}
	for _, stat in pairs(player.leaderstats:GetChildren()) do
		playerStats[stat.Name] = stat.Value
	end
	return playerStats
end

Players.PlayerRemoving:Connect(function(player)
	local playerStatsValues = getPlayerStatsValues(player)
	local success, errorMessage = pcall(function()
		playerPointsData:SetAsync("Player"..player.UserId, playerStatsValues)
	end)
	
	if success then
		print("Player's point successfully saved")
	else
		warn(errorMessage)
	end
end)
tableOfValues = {"a", "b", "c", "d"}
stringTable = table.concat(tableOfValues, "~") --use a unique delimiter
datastore:SetAsync(somekey, stringTable)

This will store a table of multiple values as a single string value inside a datastore, when you then use GetAsync or some other data store function to retrieve the data you can use string.split() to split the data up again.

Do you have any other ways? Cuz I haven’t learned a lot about string functions.

The easiest way to do this is to make a table with the player values

local tableToSave = {
	player.leaderstats.Kills.Value,
	player.leaderstats.Deaths.Value
}

and then just save it

playerPointsData:SetAsync("Player"..player.UserId, tableToSave)

You can also load the data this way (im assuming you know what pcalls are because you used them correctly:

if success and data then
	Kills.Value = data[1] -- First because that's the first one we saved
	Deaths.Value = data[2]
end

Nice! It saved the points. Thank you very much! Very easy way.

1 Like

But I think it’s better to assign the value to a key. Example:

["kills"] = player.leaderstats.Kills.Value

in order to recognize the values easier.

1 Like