✓ Accepted answer
In a data store we save data as a table to save on the number of requests needed to load / save the players data due to a limited request count.
This table is saved in a JSON format then saved (this is all managed by roblox) and then decoded giving us back the original table of data we saved. We cannot save a mixed table ie a table with both an array part and a key value part as this is not compatible with the JSON format.
To access data we use its key to get the associated data which will be nil if there is no data or the data saved. In most cases we want the key to be unique so we simply add the UserId, I would recommend that you include a prefix such as usr_ ect as you may want to use more than one key for that user.
Putting it all together:-
local Data = game:GetService('DataStoreService'):GetDataStore('Data0')
local prefix = 'user_'
game.Players.PlayerAdded:connect(function(player)
local folder = Instance.new('Folder')
folder.Name = 'Leaderstats'
local credits = Instance.new('IntValue',folder)
credits.Name = 'Credits'
local lapAmmount = Instance.new('IntValue',folder)
lapAmmount.Name = 'LapAmmount'
local plrData = Data:GetAsync(prefix .. tostring(player.UserId))
if plrData then
credits.Value = plrData[1] or 0
lapAmmount.Value = plrData[2] or 0
else
Data:SetAsync(prefix .. tostring(player.UserId), {
credits.Value,
lapAmmount.Value
})
end
end)
game.Players.PlayerRemoving:connect(function(player)
Data:SetAsync(prefix .. tostring(player.UserId), {
player.Leaderstats.Credits.Value,
player.Leaderstats.LapAmmount.Value
})
end)
This is a very basic example with duplicate code, I hope this helps.
4 comments
Use a table?
I edited the code.
You do not load the data correctly and I would not save data using the changed event as you will max the key limit.
How would I load the data correctly then? I am very new to datastores.