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

How do you save tables in a datastore properly?

Asked by 6 years ago

I want to save a table as a datastore that has many other tables inside it, but how do I?

For a visual example, I want it to be like:

local DataToSave = {PlayerStats = {logs = 25}, Items = {'Axe', 'Sword'}}

This is the code I have right now but it has an underline under the word PlayerStats line 17 saying PlayerStats is an unknown global, how do I access the table inside that table without it showing unknown global so I can set the value of 'logs' to the value inside the PlayerStats table?

local DataStore = game:GetService("DataStoreService"):GetDataStore('PlayerStats')

game.Players.PlayerAdded:Connect(function(Player)
    local leaderstats = Instance.new('Folder')
    leaderstats.Parent = Player
    leaderstats.Name = 'leaderstats'

    local logs = Instance.new('IntValue')
    logs.Parent = leaderstats
    logs.Name = 'Logs'

    local scope = 'player_' .. Player.UserId

    local savedLogs = DataStore:GetAsync(scope)

    if savedLogs then
        logs.Value = savedLogs[PlayerStats]
    end
end)

1 answer

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

When you are a value in a table and the index is a string, you need to wrap the index in quotation marks (""). You can also use "." because the key you are referencing is a string.

Also, you need to use the "logs" key in the "PlayerStats" table in order to get its value.

Here is the code:

local DataStore = game:GetService("DataStoreService"):GetDataStore('PlayerStats')

game.Players.PlayerAdded:Connect(function(Player)
    local leaderstats = Instance.new('Folder')
    leaderstats.Parent = Player
    leaderstats.Name = 'leaderstats'

    local logs = Instance.new('IntValue')
    logs.Parent = leaderstats
    logs.Name = 'Logs'

    local scope = 'player_' .. Player.UserId

    local savedLogs = DataStore:GetAsync(scope)

    if savedLogs then
        logs.Value = savedLogs.PlayerStats.logs -- I use "." like how you use "game.Players" because the keys are strings.
    end
end)

If you have any questions, please leave them in the comments. Thanks.

Ad

Answer this question