-
What do you want to achieve? Keep it simple and clear!
I want to know how I could improve my Datastore below, Perfectionize so the datastore can easily hold 40+ Values with a minimal of 12 players in a Server. -
What is the issue? Include screenshots / videos if possible!
There is no issue yet, I just want to know how I could improve this. The code is below. -
What solutions have you tried so far? Did you look for solutions on the Developer Hub?
I’ve tried to ask several servers, but no one answered.
local players = game:GetService("Players")
local dataStoreService = game:GetService("DataStoreService")
local saveDataStore = dataStoreService:GetDataStore("DataStore11")
local StatTable = require(game.ReplicatedStorage.Functions.StatTable)
players.PlayerAdded:Connect(function(plr)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = plr
for i, v in ipairs(StatTable.Stats) do
local stat = Instance.new("StringValue")
stat.Name = v
stat.Parent = leaderstats
end
local DataId = Instance.new("IntValue")
DataId.Value = 0
DataId.Parent = plr
local data = saveDataStore:GetAsync(plr.UserId)
if data then
for name,value in pairs(data.leaderstats) do
leaderstats[name].Value = value
end
end
end)
local function serializePlayerData(plr)
local saveData = {leaderstats = {} }
for _, stat in pairs(plr.leaderstats:GetChildren()) do
saveData.leaderstats[stat.Name] = stat.Value
end
return saveData
end
local function savePlayerData(plr)
local saveData = serializePlayerData(plr)
saveDataStore:UpdateAsync(plr.UserId, function(oldValue)
local PreviousData = oldValue or {DataId = 0}
if saveData.DataId == PreviousData.DataId then
saveData.DataId = saveData.DataId + 1
return saveData
else
return nil
end
end)
end
local RunService = game:GetService("RunService")
if not RunService:IsStudio() then
game:BindToClose(function()
local plr = game.Players:GetPlayers()
local n = 0
for _, Player in pairs(plr) do
task.spawn(function()
pcall(savePlayerData, Player)
n += 1
end)
end
while n < #plr do task.wait(1) end
end)
end