I’ve been trying to help a friend code a simulator, trying to save a table of data to datastore, yet I have forgotten how to do so, the error and code is below.
local DataStoreService = game:GetService("DataStoreService")
local function leaderboardSetup(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local Coins = Instance.new("NumberValue")
Coins.Name = "Coins"
Coins.Value = 0
Coins.Parent = leaderstats
local Rebirths = Instance.new("NumberValue")
Rebirths.Name = "Rebirths"
Rebirths.Value = 0
Rebirths.Parent = leaderstats
end
------------
local function dataSaver(player)
local dataTable = {
}
for _,value in player:WaitForChild("leaderstats"):GetChildren() do
dataTable[value.Name] = value.Value
end
print(dataTable)
local data = DataStoreService:GetDataStore("PlayerData")
data:SetAsync(player.UserId.."_Stats", dataTable)
end
game.Players.PlayerRemoving:Connect(dataSaver)
game.Players.PlayerAdded:Connect(leaderboardSetup)
This is because you need to use some type of dictionary, you should also use pcall functions to make sure the function is “protected”
Try out this script
local DataStoreService = game:GetService("DataStoreService")
local function leaderboardSetup(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local Coins = Instance.new("NumberValue")
Coins.Name = "Coins"
Coins.Value = 0
Coins.Parent = leaderstats
local Rebirths = Instance.new("NumberValue")
Rebirths.Name = "Rebirths"
Rebirths.Value = 0
Rebirths.Parent = leaderstats
end
local function dataSaver(player)
local dataStore = DataStoreService:GetDataStore("PlayerData")
local leaderstats = player:FindFirstChild("leaderstats")
if leaderstats then
local dataTable = {}
for _, value in ipairs(leaderstats:GetChildren()) do
if value:IsA("NumberValue") then
dataTable[value.Name] = value.Value
end
end
local success, error = pcall(function()
dataStore:SetAsync(player.UserId.."_Stats", dataTable)
end)
if success then
print("Player data saved successfully.")
else
warn("Error saving player data:", error)
end
end
end
game.Players.PlayerRemoving:Connect(dataSaver)
game.Players.PlayerAdded:Connect(leaderboardSetup)