Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to JSONEncode DataStores?

Asked by
wackem 50
9 years ago

Yes, I know this isn't a request site, but I'm not requesting, I'm asking for assistance, nothing on the Wiki helps and I can't find a tutorial. The reason I need to JSONEncode is because whenever I update my game it sets all the player's values to the default. This is my current script:

DataStore = game:GetService("DataStoreService"):GetDataStore("Values")


game.Players.PlayerAdded:connect(function(plr)
    local stat = Instance.new("IntValue", plr)
    stat.Name = "leaderstats"   

    local cred = Instance.new("IntValue", stat)
    cred.Value = 0
    cred.Name = "Credits"

    local save = "plr-"..plr.userId

    local savedVals = DataStore:GetAsync(save)

    if savedVals then
        cred.Value = savedVals[1]
    else
        local val = {cred.Value}
        DataStore:SetAsync(save, val[1])
    end
end)

game.Players.PlayerRemoving:connect(function(plr)
    local val = {plr.leaderstats.Credits.Value}
    local save = "plr-"..plr.userId
    DataStore:SetAsync(save, val[1])
end)

1 answer

Log in to vote
0
Answered by 9 years ago

Just save "cred"s value. You don't need to turn it into a table. The reason it loads as 0 is because you're setting it to 0 on line 9. Just don't turn it into a table and use GetAsync to get the credits.


Final Product

DataStore = game:GetService("DataStoreService"):GetDataStore("Values")


game.Players.PlayerAdded:connect(function(plr)
    local val = 0
    local savedVals = DataStore:GetAsync(save)
    local save = "plr-"..plr.userId
    if savedVals then
        val = savedVals
    else
        val = 0
        DataStore:UpdateAsync(save,function() return 0 end))
    end

    local stat = Instance.new("IntValue", plr)
    stat.Name = "leaderstats"   

    local cred = Instance.new("IntValue", stat)
    cred.Value = val
    cred.Name = "Credits"
end)

game.Players.PlayerRemoving:connect(function(plr)
    local val = plr.leaderstats.Credits.Value
    local save = "plr-"..plr.userId
    DataStore:UpdateAsync(save,function() return cred.Value end))
end)

Hope it helps!

Ad

Answer this question