Saving a table/ dictionary in a datastore

I’m trying to save this dictionary in a datastore it prints success and no error shows but it doesn’t work. If anyone can check if I’m doing any mistake here would be awesome.

local dss = game:GetService("DataStoreService")
local ds = dss:GetDataStore("coinstats")

game.Players.PlayerAdded:Connect(function(plr)
    local leaderstats = Instance.new("Folder", plr)
    leaderstats.Name = "leaderstats"
    
    local coins = Instance.new("IntValue", leaderstats)
    coins.Name = "Coins"
    coins.Value = 0
    
    local test = plr:FindFirstChild("Test")
    if not test then
        game.ServerStorage.Test:Clone().Parent = plr
    end
    
    local tosave = {
        coins = plr.leaderstats.Coins.Value,
        ownedTrails = {}
    }
    
    for i, v in pairs(plr.Test:GetChildren()) do
        tosave.ownedTrails[v.Name] = v.Value
    end
    
    local data 
    local ss, err = pcall(function()
        data = ds:GetAsync(plr.UserId)
    end)
    if ss then
        print("found")
        tosave = data
    else print("err get")
    end
end)

game.Players.PlayerRemoving:Connect(function(plr)
    local tosave = {
        coins = plr.leaderstats.Coins.Value,
        ownedTrails = {}
    }

    for i, v in pairs(plr.Test:GetChildren()) do
        tosave.ownedTrails[v.Name] = v.Value
    end
    local ss, err = pcall(function()
        ds:SetAsync(plr.UserId, tosave)
    end)
    if ss then print("success saved")
    end
end)

The “saving part” of it works but it doesn’t load the data properly.

This doesn’t work because the Coins intValue never gets set and the ownedTrails loads from tosave, which is empty.

To fix this you would have to move this part just below local tosave.

and you need to add

plr.leaderstats.Coins.Value = tosave.coins
1 Like

Thank you very much, it works fine now :slight_smile:

There’s some problem coming, it saves the coins but doesn’t save the children of “Test” folder