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

Why can't I save a table with more than 1 value in my datastore?

Asked by 6 years ago

I'm trying to save 2 values, strength and stamina. I want to save them both as a table in 1 datastore. I know this is possible, but it just isn't working. What am I doing wrong?

-- Code that gives the player their saved stats when they join
local players = game:GetService("Players")
local DSService = game:GetService('DataStoreService'):GetDataStore('SecretTokenAboutAvatarwwww')

players.PlayerAdded:Connect(function(player)
    local PlayerStats = Instance.new('Folder', player)
    PlayerStats.Name = 'PlayerStats'
    local str = Instance.new('IntValue', PlayerStats)
    str.Name = 'Strength'
    local stm = Instance.new('IntValue', PlayerStats)
    stm.Name = 'Stamina'

    local uniquekey = "stats-"..player.userId
    local GetSaved = DSService:GetAsync(uniquekey)
    if GetSaved then
        print(GetSaved[1], GetSaved[2])
        str.Value = GetSaved[1]
        stm.Value = GetSaved[2]
    else
        DSService:SetAsync(uniquekey, {0,0})
        str.Value = 0
        stm.Value = 0
    end
end)
-- Code that saves their data when they leave
local Players = game:GetService("Players")
local DSService = game:GetService('DataStoreService'):GetDataStore('SecretTokenAboutAvatarwwww')

Players.PlayerRemoving:Connect(function(player)
    local userId = "stats-"..player.userId
    local data = {player.PlayerStats.Strength.Value,player.PlayerStats.Stamina.Value}
    if data then
        local success, result = pcall(function()
            DSService:UpdateAsync(userId, data)
        end)
        if not success then
            warn(result)
        end
    end
end)

1 answer

Log in to vote
2
Answered by 6 years ago
Edited 6 years ago

UpdateAsync()

UpdateAsync takes the 2nd parameter as a function, not a table nor value. then you'd return the new value. userId is deprecated, use UserId.

-- the other stuff

local Players = game:GetService("Players")
local DSService = game:GetService('DataStoreService'):GetDataStore('SecretTokenAboutAvatarwwww')

Players.PlayerRemoving:Connect(function(player)
    local userId = "stats-"..player.UserId
    local data = {player.PlayerStats.Strength.Value,player.PlayerStats.Stamina.Value}

    if data then
        local success, result = pcall(function()
    DSService:UpdateAsync(userId, function(oldvalues)
        local newtable = data or oldvalues

        return newtable -- return the table
        end)

        if not success then
            warn(result)
        end
    end
end)
0
Thanks a ton, I had no idea I had to return the value. repgainer3 35 — 6y
Ad

Answer this question