Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Trying To Save A Table Onto A Data Store Is Not Saving?

Basically I Save The Items In a Backpack And Then When They Rejoin It Gives Them Those Items But A Problem Is That When They Return The Table Is Blank Even Though When They Leave The Table Does Save

Here Is My Script

local DataStore = game:GetService("DataStoreService")
local Data = DataStore:GetDataStore("MS_PopItTrading_Inventory_Data")

game.Players.ChildAdded:Connect(function(Plr)
	local Key = Plr.UserId

	if Data:GetAsync(Key) == nil then
		local Inventory = {"Blank"}
		Data:SetAsync(Key,Inventory)
		print(Data:GetAsync(Key))
	else
		for i, value in pairs(Data:GetAsync(Key)) do
			local Pop = game.Lighting.PopIts:FindFirstChild(value)
			if Pop then
				local Clone = Pop:Clone()
				Clone.Parent = Plr.Backpack
			end
		end
		print(Data:GetAsync(Key))
	end
end)

game.ReplicatedStorage.InventorySave.OnServerEvent:Connect(function(Plr)
	local Key = Plr.UserId
	local Inventory= {}

	local Amount = 0

	for i,v in pairs(Plr.Backpack:GetChildren()) do
		local Amount = Amount + 1
		table.insert(Inventory,Amount,v.Name)
	end
	
	local Success, Error = pcall(function()
		Data:SetAsync(Key,Inventory)
	end)
	if Error then
		warn(Error)
	end
end)

1 answer

✓ Accepted answer

There are a few things that I recommend.

DataStore strings should be keys DataStore keys must be strings. I recommend you even do something like:

local Key = "Inventory_" .. tostring(Plr.UserId)

Limit your use of GetAsync() Next point I'd like to make is the amount of times that you're calling GetAsync(). There are certain limits which can be easily exceeded if you are not careful. Make use of variables, as they're extremely useful. The player data you retrieve at one point is highly unlikely to change less than a second later.

Use the PlayerAdded event I noticed you used game.Players.ChildAdded. This works, but it's not optimal, as ROBLOX offers a much more secure event: Player Added

Simplify your table.insert() On line 30 of your code, I notice how you make use of a variable Amount to add items to the list. This of course works fine, but you have two simpler options:

for i,v in ipairs(Plr.Backpack:GetChildren()) do
    table.insert(Inventory, i, v.Name)
end
for _, v in ipairs(Plr.Backpack:GetChildren()) do
    table.insert(Inventory, v.Name)
end

The last option is in my opinion preferable, as if the second argument in table.insert() is your value, the function will simply append the item to the table. You may have also noticed I changed pairs to ipairs. Although the difference is small, ipairs has been proven to be roughly 20% faster. You can read a great answer by sleitnick on how loops work here!

Good luck!

This discussion is preserved as it was. New answers, comments, and votes are closed.