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:

1local 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?

01local DataStore = game:GetService("DataStoreService"):GetDataStore('PlayerStats')
02 
03game.Players.PlayerAdded:Connect(function(Player)
04    local leaderstats = Instance.new('Folder')
05    leaderstats.Parent = Player
06    leaderstats.Name = 'leaderstats'
07 
08    local logs = Instance.new('IntValue')
09    logs.Parent = leaderstats
10    logs.Name = 'Logs'
11 
12    local scope = 'player_' .. Player.UserId
13 
14    local savedLogs = DataStore:GetAsync(scope)
15 
16    if savedLogs then
17        logs.Value = savedLogs[PlayerStats]
18    end
19end)

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:

01local DataStore = game:GetService("DataStoreService"):GetDataStore('PlayerStats')
02 
03game.Players.PlayerAdded:Connect(function(Player)
04    local leaderstats = Instance.new('Folder')
05    leaderstats.Parent = Player
06    leaderstats.Name = 'leaderstats'
07 
08    local logs = Instance.new('IntValue')
09    logs.Parent = leaderstats
10    logs.Name = 'Logs'
11 
12    local scope = 'player_' .. Player.UserId
13 
14    local savedLogs = DataStore:GetAsync(scope)
15 
16    if savedLogs then
17        logs.Value = savedLogs.PlayerStats.logs -- I use "." like how you use "game.Players" because the keys are strings.
18    end
19end)

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

Ad

Answer this question