Hello everyone!
As said in title, this is my first time working with data stores
I would want you to check out my code and suggest me something to improve it.
The main point of how script is supposed to work is to save players data of points, survivals, kills but also some ârolesâ (which are not fully implemented yet) and playerâs purchases in shop that I will surely add in future!
local DataStoreService = game:GetService("DataStoreService")
local PlayersData = DataStoreService:GetDataStore("PlayersData_TEST")
local Players = game:GetService("Players")
local function CreateLeaderstatsFolder(player: Player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats" -- The name of the folder must be leaderstats oherwise it will not work
leaderstats.Parent = player
local points = Instance.new("IntValue")
points.Name = "Points"
points.Value = 100
points.Parent = leaderstats
local survivals = Instance.new("IntValue")
survivals.Name = "Survivals"
survivals.Value = 0
survivals.Parent = leaderstats
local kills = Instance.new("IntValue")
kills.Name = "Kills"
kills.Value = 0
kills.Parent = leaderstats
end
local function LoadStats(player: Player, data: DataStore)
local playerLds = player:FindFirstChild("leaderstats")
playerLds.Points.Value = data.points
playerLds.Survivals.Value = data.survivals
playerLds.Kills.Value = data.kills
end
local function deepCopy(original)
local copy = {}
for k, v in pairs(original) do
if type(v) == "table" then
v = deepCopy(v)
end
copy[k] = v
end
return copy
end
local dataTemplate = {
points = 100,
survivals = 0,
kills = 0,
isBanned = false,
isAdmin = false,
isOG = false,
isContentCreator = false
}
Players.PlayerAdded:Connect(function(player)
CreateLeaderstatsFolder(player)
local success, errorMsg = pcall(function()
local data = PlayersData:GetAsync(player.UserId)
if data == nil then
data = deepCopy(dataTemplate)
PlayersData:SetAsync(player.UserId, dataTemplate)
end
LoadStats(player, data)
end)
if success then warn(player.Name.."'s data is successfully loaded!") else
player:Kick("Failed to load player data!")
error(player.Name.."'s DataLoadError: "..errorMsg)
end
end)
Players.PlayerRemoving:Connect(function(player)
local ldstats = player:FindFirstChild("leaderstats")
local dataTable = {
points = ldstats.Points.Value,
survivals = ldstats.Survivals.Value,
kills = ldstats.Kills.Value,
isBanned = false,
isAdmin = false,
isOG = false,
isContentCreator = false
}
local success, errorMsg = pcall(function()
PlayersData:SetAsync(player.UserId, dataTable)
end)
if success then warn(player.Name.."'s data is successfully saved!") else error(player.Name.."'s DataSaveError: "..errorMsg) end
end)