I've seen many pages of people asking how to save datastores to a table and people have also recommended me to do it but i don't understand what are the benefits of doing so. I wanted to give it a try so this is what i've attempted to do but i'm not sure if i'm doing it right.
--//Service
local dataService = game:GetService('DataStoreService')
--//DataStores
local dataStores = {
goldData = dataService:GetDataStore('GoldData'),
silverData = dataService:GetDataStore('SilverData')
}
--//Save Function
function saveData(dataName, playerId, value)
dataName:SetAsync(playerId, value)
end
--//PlayerAdded
game.Players.PlayerAdded:Connect(function(players)
local ID = players.UserId
local folder = Instance.new('Folder')
folder.Name = 'leaderstats'
folder.Parent = players
local gold = Instance.new('IntValue')
gold.Name = 'Gold'
gold.Parent = folder
local silver = Instance.new('IntValue')
silver.Name = 'Silver'
silver.Parent = folder
local loadGoldData = nil
local loadSilverData = nil
pcall(function()
loadGoldData = dataStores.goldData:GetAsync(ID)
loadSilverData = dataStores.silverData:GetAsync(ID)
end)
--//If player has data then load it
if loadGoldData and loadSilverData ~= nil then
gold.Value = loadGoldData
silver.Value = loadSilverData
print('Data Loaded')
else
--//Else player is new
gold.Value = 10
silver.Value = 100
print('New Player')
end
end)
--//PlayerRemoving
game.Players.PlayerRemoving:Connect(function(players)
local ID = players.UserId
saveData(dataStores.goldData, ID, players:WaitForChild('leaderstats'):WaitForChild('Gold').Value)
saveData(dataStores.silverData, ID ,players:WaitForChild('leaderstats'):WaitForChild('Silver').Value)
end)
--//BindToClose
game:BindToClose(function()
for i,v in pairs(game.Players:GetPlayers()) do
if v then
v:Kick('The Server Has Shut Down')
end
end
wait(3)
end)

1 comment
Thanks, now i understand!