Feedback on DataStore script

Hi all, (first topic)

I’m new (-ish) to programming here on Roblox, and I am just looking for feedback on my DataStore script. More specifically my code to access and use DataStore when a player joins. Except for the first comment all other comments I added here to make it easier to understand.


local MaxAttempts = 3
local AttemptCoolDown = 5

local StarterData = {
	Gold = 50
}

local function GetPlayerData (Player)

	local WaitForPlayer = Player.CharacterAdded:Wait()
	
	local PlayerID = Player.UserId
	local Attempts = 0
	
	local Works
	local SavedPlayerData

	repeat	

		Works, SavedPlayerData = pcall (DataStore.GetAsync, DataStore, PlayerID)	

		if Works then
			if SavedPlayerData ~= nil then
				
				print (SavedPlayerData["Gold"])

				break
			else 
				if SavedPlayerData == nil then
					
					TestService:Warn (false, string.format("Creating data for: %i!", PlayerID))
					
					Works = pcall (DataStore.SetAsync, DataStore, PlayerID, StarterData)
					
					if not Works then
						TestService:Error (string.format("Could not create data for: %i!", PlayerID))
					end
				end
			end
		else 
			if not Works then
				
				Attempts += 1
				
				TestService:Error (string.format("Could not get data for: %i!", PlayerID))
			end
		end
		
		wait(AttemptCoolDown)
		
	until Attempts >= MaxAttempts
end


PlayerService.PlayerAdded:Connect (GetPlayerData)

This script attempts to access the data 3 times.

Specifically I’m wondering about a few things:

  • is this the most efficient way to do this?
  • is it easy to understand (Spacing, variable names, (remember only the first comment is in my actual code)

Anything else will help, thank you very much! (any comments on my topic writing will also help)

Edit: Made some new changes to the code, also simplified examples.

1 Like

not bad however you should add a debug feature so you know what you did wrong.

1 Like

Debug? Do you mean instead of the print statements? EDIT: Oh I understand now, thank you!