The new version of the for loop was meant for if they have data, I fixed it up for you:
local DataStore = game:GetService("DataStoreService"):GetDataStore("DataSaveService")
game.Players.PlayerAdded:Connect(function(player)
local key = "player-"..player.UserId
local savedValues = DataStore:GetAsync(key)
local leaderstatsFolder = Instance.new("Folder")
leaderstatsFolder.Name = "leaderstats"
leaderstatsFolder.Parent = player
if(savedValues) then
for i,v in pairs(script.leaderstats:GetChildren()) do
local stat = Instance.new(v.ClassName)
stat.Name = v.Name
stat.Value = savedValues[v.Name] or v.Value
end
else
local save = {}
for i, v in pairs(script.leaderstats:GetChildren()) do
local stat = Instance.new(v.ClassName)
stat.Name = v.Name
stat.Value = v.Value
stat.Parent = player.leaderstats
save[v.Name] = v.Value
end
DataStore:SetAsync(key, save)
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local key = "player-"..player.UserId
local save = {}
for i, v in pairs(player.leaderstats:GetChildren()) do
save[v.Name] = v.Value
end
DataStore:SetAsync(key, save)
end)
This may not be a total concern yet, put you should look into using pcalls for datastore functions as they can error.
You can read more here: