Datastore system not saving

Im trying to make a datastore system that uses module scripts, but for some reason it won’t save, any ideas why?

local Plrs = game:GetService("Players")
local Dss = game:GetService("DataStoreService")
local Ds = Dss:GetDataStore("GameData")

local SessionData = require(script.SessionData)
local PlrTemplate = require(script.PlayerTemplate)

function Save(plr)
	if SessionData[plr.UserId] then
	local success, errorMsg, attempt = nil, nil, 1	
		repeat success, errorMsg = pcall(function() 
				print(SessionData[plr.UserId])
		Ds:SetAsync(plr.UserId, SessionData[plr.UserId])
	end)
	if not success then warn(errorMsg) task.wait(3) 
		attempt+=1
	end
	until success or attempt == 5
		if success then print("Data saved for", plr.Name) else warn("Unable to save for", plr.Name) end
	end
end

function Load(plr)
	local success, playerdata, attempt = nil, nil, 1
	repeat success, playerdata = pcall(function()
			print(Ds:GetAsync(plr.UserId))
		return Ds:GetAsync(plr.UserId)
	end)
	attempt+=1
	until success or attempt == 5
	if success then 
		print("Connected to database") 
		if not playerdata then
			print("Assigning defualt data")
			playerdata = {
				["Tokens"] = 10,
			}
		end
		SessionData[plr.UserId] = PlrTemplate.new()
		print(SessionData[plr.UserId])
		SessionData[plr.UserId]:AddTokens(10)
		print(SessionData[plr.UserId])
	else
		warn("Unable to get data for", plr.Name)
		plr:Kick("Unable to load data. Please try again later")
	end
end

function ServerShutdown()
	print("Server shutting down")
	for i, plr in ipairs(SessionData) do
		task.spawn(function()
			Save(plr)		
		end)
	end
end

function PlayerAdded(plr: Player)
	Load(plr)
end

function PlayerLeaving(plr: Player)
	Save(plr)
end

Plrs.PlayerAdded:Connect(PlayerAdded)
Plrs.PlayerRemoving:Connect(PlayerLeaving)
game:BindToClose(ServerShutdown)
1 Like

You don’t use pcalls like this, the second argument for pcall is an errorMessage like what you did for saving data. Try to do this:

function Load(plr)
	local success, errorMsg, playerdata, attempt = nil, nil, nil, 1
	repeat success, errorMsg = pcall(function()
			playerdata = Ds:GetAsync(plr.UserId)
		end)
		attempt+=1
	until success or attempt == 5
	if success then 
		print("Connected to database") 
		if not playerdata then
			print("Assigning default data")
			playerdata = {
				["Tokens"] = 10,
			}
		end
		SessionData[plr.UserId] = PlrTemplate.new()
		print(SessionData[plr.UserId])
		SessionData[plr.UserId]:AddTokens(10)
		print(SessionData[plr.UserId])
	else
		warn("Unable to get data for", plr.Name)
		plr:Kick("Unable to load data. Please try again later")
	end
end
2 Likes

still doesn’t seem to save ;-;
instead of printing tokens = 20 it prints tokens = 10

I tried printing player data in the load function, seems it is able to get the data properly, just cant seem to tell if it exists or not, as it acts like the player doesn’t have data and assigns the default data instead.