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

How to convert a DataStore model to a table?

Asked by
Radstar1 270 Moderation Voter
7 years ago

So I read an idea on where you save a player's data as a model in ReplicatedStorage and put the values inside that model. Whenever the model changes then it converts into a table and saves those changes. The benefit of this is giving the data a visual appearance

----Question------ How would I go about converting the inside of the model to a table? I'm thinking somewhere along the lines of

Model.Changed:connect(function()
    for i,v in pairs(Model:GetChildren()) do
    v:UpdateAsync(player.UserId,v)
    end
end)

Is this the correct way?

1 answer

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

Solution

Since there is no differentiation in the key that you save your data to, it is going to keep being overwritten until the last index in the Model:GetChildren() table.

I suggest you construct a dictionary, and save that :)


Tips

Saving everytime the data is changed is a bit overkill - Just save when the player leaves.

And personally, I like to simply store all player data as descendants of the player object - especially since the in-game leaderboard format requires this. But that's just my preference..

  • Note: connect is deprecated, use Connect!

Code

--Define datastore
local ds = game:GetService("DataStoreService"):GetDataStore("Stats")

--PlayerRemoving event
game.Players.PlayerRemoving:Connect(function(p)
    local data = {}; --Define array
    --Reference stats holder
    local Model = game.ServerStorage:FindFirstChild(p)
    for i,v in pairs(Model:GetChildren()) do
        data[v.Name] = v.Value --Add an index to the dictionary
    end
    ds:UpdateAsync(player.UserId,data)
end)
0
Thank you so much! Radstar1 270 — 7y
Ad

Answer this question