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

How to save stats using table?

Asked by 7 years ago

So I have bool values in a folder but depending on the player there are different amounts of boolvalues so I need to saving all using a table. I am not quiet sure how to do so.

local datastore = game:GetService("DataStoreService"):GetDataStore("Cards")

game.Players.PlayerRemoving:connect(function(player)
player:WaitForDataReady() -- make sure we aren't looking for leaderstats before they are created
wait(2) -- just in case
local stats = player:FindFirstChild("Cards"):GetChildren()

for i = 1, #stats do -- creates a loop for all the stats
print(stats[i].Name)
datastore:SetAsync(stats[i].Name, stats[i].Value)
end
end)

-- Loading dem stats
game.Players.PlayerAdded:connect(function(newplayer)
newplayer:WaitForDataReady() -- make sure we aren't looking for leaderstats before they are created
wait(2) -- just in case
local stats2 = newplayer:FindFirstChild("Cards"):GetChildren()
for i = 1, #stats2 do
stats2[i].Value = datastore:GetAsync(stats2[i].Name)
end
end)
0
You don't need WaitForDataReady. cabbler 1942 — 7y

1 answer

Log in to vote
0
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
7 years ago
Edited 7 years ago

Seems like you're doing this mostly correct, but you neglected to keep a constant key.

DataStores take in keys and values, much like normal tables, and in order for you to be able to retrieve the Player's data you need to reference the Player's UserId within the key - otherwise the data is kinda just lost and multiple clients are saving to the same key yafeel?

Would look like this:

local datastore = game:GetService("DataStoreService"):GetDataStore("Cards")

game.Players.PlayerRemoving:connect(function(player)
    local stats = player:FindFirstChild("Cards"):GetChildren()
    for i = 1, #stats do
    --Now that the stat name is tied with the Player's UserId, you can retrieve it.
        datastore:SetAsync(player.UserId.."|"..stats[i].Name, stats[i].Value)
    end
end)

game.Players.PlayerAdded:connect(function(newplayer)
    newplayer:WaitForDataReady()
    local stats2 = newplayer:WaitForChild("Cards"):GetChildren()
    for i = 1, #stats2 do
        stats2[i].Value = datastore:GetAsync(newplayer.UserId.."|"..stats2[i].Name)
    end
end)
0
It isnt saving when i add a stat to the folder, leave and ask it to print the value it says the value isnt there Bylocks 1 — 7y
0
Hmm.. perhaps try changing the DataStore name? Also make sure this is a regular Script in Workspace or ServerScriptStorage Goulstem 8144 — 7y
Ad

Answer this question