How to save tables in Data Store

The title speaks for itself.
Basically I want to store a folder (not “leaderstats”) to a table, and then Set it into a Data Store

I saw a huge amount of tutorials about this theme, but nothing was helpful for me.

For now I am using a max limit of Data Stores (5), and because of that the Values do not save sometimes.

Any help will be appreciated!

1 Like

I’d recommend reading up a bit more on DataStores. There’s little reason and benefit to use 2 separate DataStores, let alone 5.

You can store a folder (and really anything!) in a DataStore through serialization. You’ll basically have to translate the folder into a Lua table with simply typed objects (think strings and numbers). When the player rejoins the game, you can read this table and deserialize their data to recreate the same folder as before.

2 Likes
local Players = game:GetService("Players")
local DataStores = game:GetService("DataStoreService")
local DataStore = DataStores:GetDataStore("DataStore")
local ProtectedCall = pcall

local function LoadData(Player)
	local Success, Result = ProtectedCall(function()
		return DataStore:GetAsync("Data_"..Player.UserId)
	end)
	
	if Success then
		if Result then
			if type(Result) == "table" then
				Player.Leaderstats:FindFirstChildWhichIsA("BoolValue").Name = Result[1]
				Player.Leaderstats:FindFirstChildWhichIsA("BoolValue").Value = Result[2]
			end
		end
	end
end

local function SaveData(Player)
	local Leaderstats = Player.Leaderstats
	local Data = {}
	for _, Leaderstat in ipairs(Leaderstats:GetChildren()) do
		table.insert(Data, {Leaderstat.Name, Leaderstat.Value})
	end
end

local function CreateStats(Player)
	local Leaderstats = Instance.new("Folder")
	Leaderstats.Name = "Leaderstats" --Intentionally made it different from the default "leaderstats".
	Leaderstats.Parent = Players
	
	local Bool = Instance.new("BoolValue")
	Bool.Parent = Leaderstats
	
	return true
end

local function OnPlayerAdded(Player)
	local Leaderstats = CreateStats(Player)
	repeat
		task.wait()
	until Leaderstats
	
	LoadData(Player)
end

local function OnPlayerRemoving(Player)
	SaveData(Player)
end

Players.PlayerAdded:Connect(OnPlayerAdded)
Players.PlayerRemoving:Connect(OnPlayerRemoving)

Here’s a quick example script of loading/saving same instances which end with the “Value” suffix. It would be helpful if you provided your own script attempts and some context regarding the data you’re attempting to save.

3 Likes