[I'm trying to use data store to save money. But it is not loading properly or at least what I think it is. Anyway here the code.


local PlayerDataManager = {}

local DataStoreService = game:GetService("DataStoreService")
local playerData = DataStoreService:GetDataStore("PlayerData01")

local sessionData = {}

local timer = 60
 
-- Function that other scripts can call to change a player's stats
function PlayerDataManager:ChangeStat(player, statName, value)
	local playerUserId = "Player_" .. player.UserId
	assert(typeof(sessionData[playerUserId][statName]) == typeof(value), "ChangeStat error: types do not match")
	if typeof(sessionData[playerUserId][statName]) == "number" then
		sessionData[playerUserId][statName] = sessionData[playerUserId][statName] + value
	else
		sessionData[playerUserId][statName] = value
	end
end
	
-- Function to add player to the 'sessionData' table
local function setupPlayerData(player)
	local playerUserId = "Player_" .. player.UserId
	local data
	local success, err = pcall(function()
	    playerData:UpdateAsync(playerUserId, function(playerData)
		   data = playerData
        end)
    end)

if success then
    if data then
	-- Data exist for this player
	sessionData[playerUserId] = DataStoreService
    else
	-- Player doesn't have existing data
	sessionData[playerUserId] = {Money=10000}
    end
else
	warn("Cannot set up data for player!")
end
end

-- function to save player's data
local function savePlayerData(playerUserId)
	if sessionData[playerUserId]then
		local success, err = pcall(function()
		playerData:SetAsync(playerUserId, sessionData[playerUserId])
		end)
		if not success then
			warn("Cannot save data for player!")
		end
	end
end

--Function to save player data on exit
local function saveOnExit(player)
	local playerUserId = "Player_" .. player.UserId
	savePlayerData(playerUserId)
end

--Function to periodically save player data
local function autoSave()
	while wait(timer)do
		print("saving")
		for playerUserId, data in pairs(sessionData)do
			savePlayerData(playerUserId)
		end
	end
end

--returns the info a player wants
function PlayerDataManager:GetMoney(player)
local playerUserId = "Player_" .. player.UserId
print(sessionData[playerUserId])
    local cash = sessionData[playerUserId]["Money"]
print(cash)
return cash
end

--Starts autoSave
spawn(autoSave)

-- Connect 'setupPlayerData()' function to 'PlayerAdded' event
game.Players.PlayerAdded:Connect(setupPlayerData)
game.Players.PlayerRemoving:Connect(saveOnExit)

return PlayerDataManager

and here's the error i got.

https://gyazo.com/b95d30795659ade3b13abf0be4a6c645

2 comments

2

This is from the wiki.

0

Oh...I found one mistake.