DataStore for table not saving

Hello!

I am trying to save a players inventory with strings in the folder. The folder is stored in the player, and it will save. But sometimes the Data gets lost and I loss all my data in that folder. How can I fix this?

Here is my script:

local DataStore = game:GetService("DataStoreService"):GetDataStore("GunSaving")

local Players = game:GetService("Players")

local function addFolderGuns(player)
	local folder = Instance.new("Folder")
	folder.Name = "myInventory"
	folder.Parent = player

	local data

	local success, errorMsg = pcall(function()
		data = DataStore:GetAsync(player.UserId)
	end)

	if data ~= nil then
		if data.Inventory then
			for index,inventory  in pairs(data.Inventory) do
				local bool = Instance.new("StringValue",folder); bool.Name = inventory
			end
		end
	else
		-- New player
		print("A new player has joined")
	end
	
	if success then
		print("Successfully loaded")
	else
		warn(errorMsg)
	end
end

game.Players.PlayerAdded:Connect(addFolderGuns)

for _, player in pairs(Players:GetPlayers()) do
	spawn(function()
		addFolderGuns(player)
	end)
end

game.Players.PlayerRemoving:Connect(function(plr)
	local data = {}

	data.Inventory = {}

	for i,v in pairs(plr.myInventory:GetChildren()) do
		table.insert(data.Inventory,v.Name)
	end

	local success, errorMsg = pcall(function()
		DataStore:SetAsync(plr.UserId,data)
	end)

	-- if its succeed then the data is saved else we got an error

	if success then 
		print("Succesfully saved") 
	else 
		warn(errorMsg) 
	end

end)

local function gameBindSave(plr)
	local data = {}

	data.Inventory = {}

	for i,v in pairs(plr.myInventory:GetChildren()) do
		table.insert(data.Inventory,v.Name)
	end

	local success, errorMsg = pcall(function()
		DataStore:SetAsync(plr.UserId,data)
	end)

	-- if its succeed then the data is saved else we got an error

	if success then 
		print("Succesfully saved") 
	else 
		warn(errorMsg) 
	end
end

game:BindToClose(function()
	wait(1.5)
	for _, v in pairs(Players:GetPlayers()) do
		gameBindSave(v)
	end
end)

Also is there a way to save a table with ProfileService?

Sincerely,

papahetfan

Yes that is possible just encode the table with HttpService and then save it

local EncodedTable = game:GetService("HttpService"):JSONEncode(table)

sorry for not helping with your main problem

Ok, I see now. But is there a tutorial or a page on the DevForum to show how I can set it up? Because I have never heard of encode before.

Here is the link do the API page
But all it does is that it takes a table and it returns the same table but in form of a string which you can save, decode or do other things with