Table not saving? DataStoreService

So I’ve been having some issues with saving tables using DataStoreService and im not quite sure what is going on. I cant tell if im missing something very easy to spot of this is something a little more complex. Does anyone know

local DataStoreService = game:GetService("DataStoreService")
local DataStoreFolder = DataStoreService:GetDataStore("TableData")
local function AssemblePlayerDataTable(Player)
	local Data = {
		Player.leaderstats.Money.Value;
		Player.leaderstats.Money.Value
	}
	return Data
end
game.Players.PlayerAdded:Connect(function(Player)
	local leaderstats = Instance.new("Folder",Player)
	leaderstats.Name = "leaderstats"
	local Money = Instance.new("NumberValue",leaderstats)
	Money.Name = "Money"
	local data
	local Key = Player.UserId.."-Money"
	local success, errormessage = pcall(function()
		data = DataStoreFolder:GetAsync(Key)
		if data and data[2] then
			Money.Value = data[2]
		end
	end)
	if success then
		print("TableDataLoaded")
	else
		warn(errormessage)
	end
	
end)

game.Players.PlayerRemoving:Connect(function(Player)
	local PlayerLeaderstats = Player.leaderstats
	local Key = Player.UserId.."-Money"
	local BroughtBackData = AssemblePlayerDataTable(Player)
	local Success, errormessage = pcall(function()
		if DataStoreFolder:GetAsync(Key) then
			DataStoreFolder:SetAsync(Key,BroughtBackData)
		end
	end)
	if Success then
		print("DataSaved")
	else
		warn(errormessage)
	end
end)

This statement will stop saving for all new players with no data. Also, to prevent data loss you should add game:BindToClose() which fires 100% when the server shuts down.

local function SaveData(Player)
	local PlayerLeaderstats = Player.leaderstats
	
	local Data = {
		PlayerLeaderstats.Money.Value; -- Assume you will change this later.
		PlayerLeaderstats.Money.Value
	}
	local Key = Player.UserId.."-Money"
	pcall(function()
		DataStoreFolder:SetAsync(Key, Data)
	end)
end

Players.PlayerRemoving:Connect(SaveData)
game:BindToClose(function()
	for _, Player in ipairs(Players:GetPlayers()) do
		SaveData(Player)
	end
end)
2 Likes

Thank you so much its now working for me!