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

How would I add items to this datastore?

Asked by 4 years ago
Edited 4 years ago

I got help previously, but I am unaware of how to add more items. Please help

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

game.Players.PlayerAdded:connect(function(player)
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player

    local Points = Instance.new("IntValue")
    Points.Name = "Points"
    Points.Parent = leaderstats

 local Gold = Instance.new("IntValue") -- Gold is the extra value I'm trying to save.
    Gold.Name = "Gold"
    Gold.Parent = leaderstats

    local key = "user-" .. player.userId

--I don't understand below here

    local storeditems = datastore:GetAsync(key)
    if storeditems then
        Points.Value = storeditems[1]
    else
        local items = {Points.Value}
        datastore:SetAsync(key, items)
    end
end)


game.Players.PlayerRemoving:connect(function(player)
    local items = {player.leaderstats.Points.Value}
    local key = "user-" .. player.userId

    datastore:SetAsync(key, items)
end)

If you for some reason need more information or code, lemme know what specific parts. I'm horrible with datastores but know the basics and some advanced works of Lua. So an in-depth explanation that covers individual parts would be nice

1 answer

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

Hello,

To solve your saving multiple items to your datastore problem you need to save data, to the datastore, as an array.

Something like this:

game.Players.PlayerRemoving:connect(function(player)
    local items = {player.leaderstats.Points.Value, player.leaderstats.Gold.Value}
    local key = "user-" .. player.userId

    datastore:SetAsync(key, items)
end)

For your information, the above code saves data to the datastore when the player leaves the game. Datastores work with saving a data to a key. In this case, your key is the players userId. SetAsync is just syntax for saving or updating data to that key.

As you are adding more data, you need to change this part too:

local storeditems = datastore:GetAsync(key)
if storeditems then
        Points.Value = storeditems[1]
    Gold.Value = storeditems[2]
end

What the above code is doing is getting all of the data for the key. For example, if the player with the userId 345237434 had 100 points and 12 gold. Then the storeditems variable would be equal to {100,12}. So, after checking if the player actually has any points or gold (if they have played the game before), we load the players amount of points and gold into the leaderstats values.

I hope this helped.

0
Thank you so much! Bearturnedhuman 48 — 4y
Ad

Answer this question