Feedback on my data store handler

This is a quick data store handler I implemented for testing. It’s bare bones so I’m all ears.

Here is what I want reviewed:

  • Readability of code,
  • How I handle data,
local DataStoreService = game:GetService("DataStoreService")
local PlayerDataStore = DataStoreService:GetDataStore("Data_Stores, Player_Data")

local Players = game:GetService("Players")

local function CheckData(player)
	
end


local function SetData(player)
	
	local playerKey = string.format("Player_Key: %s", player.UserId)
	local player_Data = player:FindFirstChild("leaderstats")
			
	local success, errormessage = pcall(function()
		for _, object in ipairs(player_Data:GetChildren()) do
			wait()
			PlayerDataStore:SetAsync(playerKey, object.Value)
		end
	end)
	
	if success then
		print(string.format("Data saved for %s", player.Name))
	else
		print(string.format("Data did not save for %s %s", player.Name, ". Error code: %s", errormessage))
	end
end


local function GetData(player)
	
	if player:IsDescendantOf(Players) then
	
		local playerKey = string.format("Player_Key: %s", player.UserId)
		local data 
		
		local tries = 0
		repeat wait(1)
		
		local success, errormessage = pcall(function()
			data = PlayerDataStore:GetAsync(playerKey)
			tries += 1
		end)
			
		if success then
			local player_Data = player:FindFirstChild("leaderstats")
			
			for _, object in ipairs(player_Data:GetChildren()) do
				object.Value = data
			end
		else
			warn(string.format("Data may not load for %s %s", player.Name, ". Debug_Code: %s", errormessage))
		end
			
		until success or tries == 3
	end
end


local function OnServerShutdown()
	for _, player in ipairs(Players:GetPlayers()) do
		SetData(player)
	end
end


local function CreateData(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local level = Instance.new("IntValue")
	level.Name = "Level"
	level.Parent = leaderstats
	
	GetData(player)
end

Players.PlayerAdded:Connect(CreateData)
Players.PlayerRemoving:Connect(SetData)
game:BindToClose(OnServerShutdown)

Changes: Made a new data store lol

2 Likes

Two comments:

  1. The nested if statements aren’t very readable,it looks better with one if statement using and.
  2. Print the error message in GiveData if there’s a failure.
2 Likes