Datastore not saving / loading

Could someone tell me why my script for datastores isn’t saving ?

local Players = game:GetService("Players")
local RepStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")
local DataStore = game:GetService("DataStoreService")

local InventoryTemplate = ServerStorage.InventoryTemplate
local AbilityStore = DataStore:GetDataStore("Abilities")

local function Load(player)
	local Inventory = InventoryTemplate:Clone()
	Inventory.Name = "Inventory"
	Inventory.Parent = player

	local PlayerId = player.UserId

	local Success, Table = pcall(function()
		AbilityStore:GetAsync(PlayerId)
	end)
	
	if Success then	
		print(Table)
		if Table == nil then return end

		local AbilitiesInInventory = Inventory.Abilities:GetChildren()

		for AbilityName, AbilityValue in pairs(Table) do
			for i, v in pairs(AbilitiesInInventory) do
				if v.Name == AbilityName then
					v.Value = AbilityValue
				end
			end
		end
	end
end

local function Save(player)
	local PlayerId = player.UserId
	local Inventory = player.Inventory
	local AbilityList = {}

	local Abilities = Inventory.Abilities:GetChildren()
	for i, v in pairs(Abilities) do
		AbilityList[v.Name] = v.value
	end

	local Success, Error = pcall(function()
		AbilityStore:UpdateAsync(PlayerId, function(OldList)
			print(AbilityList)
			return AbilityList
		end)
	end)

	if not Success then
		print(Error)
	end
end

Players.PlayerAdded:Connect(Load)
Players.PlayerRemoving:Connect(Save)

Pcall, which is a Lua global, does protect the script from any errors that implementing functions, which generally end in “Async”. If it handles the function successfully, it will return the bool true. But, if the function doesn’t coincide with the expected result, it will be false. The error message of the failure will be dropped as the second return.

The reason why your script didn’t seem to work as you anticipated it would, you used the second return of pcall as a table.

local Success, Table = pcall(function()

So, Table, as defined in code, is the error message. Unless it fails, returns nil. Here is how you can retrieve the table from the datastore.

local Table

local success, errorMessage = pcall(function()
    Table = AbilityStore:GetAsync(PlayerId)
end)

Furthermore, if a player were new to the game, they wouldn’t be registered to the datastore. By means of lacking to have the table and to continue on so, ignore the player only once. To supervise it, do

if success then
    if Table ~= nil then
        -- The rest of the script
    end
end
2 Likes