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

How do I convert a script from Data Persistence to Data Stores?

Hi! I wanted to convert my old data persistence script to use the new data stores but this doesn't save "cash" at all and I don't really know why. Can anyone point me in the right direction?

Thanks, MD

local DataStore = game:GetService("DataStoreService"):GetDataStore("Cash")
local key = "user_" .. player.userId

function saveScore(player, score)
	SetAsync(key, score)
end

function loadScore(player, clickCounter)
	local score = GetAsync(key)
	if score ~= 0 then
		clickCounter.Value = score
	end
end

function onPlayerEntered(newPlayer)
		local stats = Instance.new("IntValue")
		stats.Name = "leaderstats"
		local clicks = Instance.new("IntValue")
		clicks.Name = "Cash"  
		clicks.Value = 0
		clicks.Parent = stats
		stats.Parent = newPlayer
		loadScore(newPlayer, clicks)
end

function onPlayerRemoving(player)
	print("Attempting to save score for " .. player.Name)
	local stats = player:FindFirstChild("leaderstats")
	if (stats ~= nil) then 
		local clicks = stats:FindFirstChild("Cash") 
		if (clicks ~= nil) then
			saveScore(player, clicks.Value)
			DataStore:UpdateAsync(key, function(oldValue)
			local newValue = oldValue or 0 --oldValue might be nil
			newValue = clicks
			end)
			end
	end
end

1 comment

0

Line 2, player isn't defined.

1 answer

line 2 isn't defined because ... well you i don't know but you cant do it that way

local DataStore = game:GetService("DataStoreService"):GetDataStore("Cash")
local key = "user_"

function saveScore(player, score)
    SetAsync("user_"..player.UserId, score)
end

function loadScore(player, clickCounter)
    local score = GetAsync("user_"..player.UserId)
    if score ~= 0 then
        clickCounter.Value = score
    end
end

function onPlayerEntered(newPlayer)
        local stats = Instance.new("IntValue")
        stats.Name = "leaderstats"
        local clicks = Instance.new("IntValue")
        clicks.Name = "Cash"  
        clicks.Value = 0
        clicks.Parent = stats
        stats.Parent = newPlayer
        loadScore(newPlayer, clicks)
end

function onPlayerRemoving(player)
    print("Attempting to save score for " .. player.Name)
    local stats = player:FindFirstChild("leaderstats")
    if (stats ~= nil) then 
        local clicks = stats:FindFirstChild("Cash") 
        if (clicks ~= nil) then
            saveScore(player, clicks.Value)
            DataStore:UpdateAsync("user_"..Plasyer.UserId, function(oldValue)
            local newValue = oldValue or 0 --oldValue might be nil
            newValue = clicks
            end)
            end
    end
end


that should work

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