I am having trouble with datastores, it works but I don’t understand the code. Would you break this down for me?
local dataStore = game:GetService("DataStoreService")
local playerData = dataStore:GetDataStore("playerData")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder", player)
leaderstats.Name = "leaderstats"
local gold = Instance.new("IntValue", leaderstats)
gold.Name = "Gold"
local ID = "Player: " .. player.UserId
local data = playerData:GetAsync(ID)
if data then
gold.Value = data
else
gold.Value = 0
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local success,err = pcall(function()
local ID = "Player: " .. player.UserId
playerData:SetAsync(ID, player.leaderstats.Gold.Value)
end)
if not success then
warn(err)
end
end)
But I do understand the leaderstats. Any response it deeply appreciated!
Looking at the lower section to do with Datastores:
game.Players.PlayerRemoving:Connect(function(player)
local success,err = pcall(function()
local ID = "Player: " .. player.UserId
playerData:SetAsync(ID, player.leaderstats.Gold.Value)
end)
This first chunk runs when a Player leaves. local success, err is set up to receive the two arguments from pcall(), which runs the code inside and allows for errors to occur while not halting the Lua thread. If the function passed to pcall() runs without error, success will be true and err will be nil. However if an error occurs within pcall(), success will be false and err will contain any error information. playerData:SetAsync() is what’s used to actually write that data to the DataStore, saving it to the playerData Datastore as the Player’s UserID.
if not success then
warn(err)
end
This simply writes error information to the output if the pcall() fails.