Feedback on how I handle player data

This is my code on how I handle player data. I would like to know two things:

  • Reliability of the code: does it work 100% of the time?
  • Readability of the code: are you able to clearly understand it?
-- services

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerScriptService = game:GetService("ServerScriptService")
local RunService = game:GetService("RunService")

-- variables

local serverPlayerData = require(ServerScriptService:WaitForChild("ServerPlayerData"))
local gameData = DataStoreService:GetDataStore("GameData")
local communicationEvent = ReplicatedStorage:WaitForChild("CommunicationEvent")

-- data templates

local mainData = {
	maxExperience = 10,
	currentExperience = 0,
	money = 0,
	timeSinceLastHourlyReward = 0,
	timeSinceLastDailyReward = 0,
	currentSword = "Wooden Sword",
	unlockedSwords = {"Wooden Sword"}
}
local miscellaneousData = {
	didPlayerCheat = false,
	deathOverride = false,
	equippedSword = false,
	viewingGui = true
}

-- create data for player

local function CreatePlayerData(player)
	if player then
		local id = tostring(player.UserId)
		serverPlayerData.AddPlayer(id)
		for dataType, defaultValue in pairs(mainData) do
			local value
			local success, errorMessage = pcall(function()
				value = gameData:GetAsync(id .. dataType) or defaultValue
			end)
			if success then
				serverPlayerData.SetValue(id, dataType, value)
				communicationEvent:FireClient(player, "SetValue", {dataType, value})
			else
				warn("Error getting " .. dataType .. " of " .. id)
			end
		end
		for dataType, defaultValue in pairs(miscellaneousData) do
			serverPlayerData.SetValue(id, dataType, defaultValue)
		end
	end
end

-- save data of player

local function SavePlayerData(player)
	if player then
		local id = tostring(player.UserId)
		if not serverPlayerData.GetValue(id, "didPlayerCheat") then
			for dataType, _ in pairs(mainData) do
				local success, errorMessage = pcall(function()
					gameData:SetAsync(id .. dataType, serverPlayerData.GetValue(id, dataType))
				end)
				if not success then
					warn("Error saving " .. dataType .. " of " .. id)
				end
			end
		end
	end
end

-- save all player data on server shutdown

local function SaveAllPlayerData()
	if not RunService:IsStudio() then
		local players = Players:GetPlayers()
		for _, player in pairs(Players) do
			SavePlayerData(player)
		end
	end
end

-- event binding

Players.PlayerAdded:Connect(CreatePlayerData)
Players.PlayerRemoving:Connect(SavePlayerData)
game:BindToClose(SaveAllPlayerData)
1 Like
  1. I have not tested it so unsure.

  2. It is clear and very understandable!