How good is my DataSave script?

Everything works just wondering if anyone could give me feedback I’d appreciate it!

local DataStoreService = game:GetService("DataStoreService")
local dataStore = DataStoreService:GetDataStore("testdata1")

local function retryData(success, err, data, player)
	local count = 0
	while not success do
		if count >= 1 then
			warn("Retrying, count:", count, "\nError:", err)
			wait(7)
		end
		success, err = pcall(function()
			data = dataStore:GetAsync("Player_"..player.UserId)
		end)
		count += 1
	end
end

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new('Folder', player)
	leaderstats.Name = "leaderstats"
	
	local roomNumber = Instance.new("IntValue", leaderstats)
	roomNumber.Name = "Room"
	roomNumber.Value = 1
	
	local buttonBux = Instance.new("IntValue", leaderstats)
	buttonBux.Name = "Button Bux"
	buttonBux.Value = 0
	
	local wins = Instance.new('IntValue', leaderstats)
	wins.Name = "Wins"
	wins.Value = 0
	
	local data
	local success, err = pcall(function()
		data = dataStore:GetAsync("Player_"..player.UserId)
	end)
	
	--// Check if data exists, then if it successfully loads, else it retries
	if data then	
		if success then
			buttonBux.Value = data.ButtonBux
			wins.Value = data.Wins
		else
			retryData(success, err, data, player)
			warn(err)
		end
	end

	--// Auto-Save	
	coroutine.wrap(function()
		while wait(120) do
			local success, err = pcall(function()
				dataStore:SetAsync("Player_"..player.UserId, data)
			end)
			
			if success then
				print('AUTO-SAVED')
			else
				warn(err)
			end
		end
	end)()
	
end)


game.Players.PlayerRemoving:Connect(function(player)
	local data = {
		ButtonBux = player.leaderstats["Button Bux"].Value,
		Wins = player.leaderstats.Wins.Value
	}
	
	local success, err = pcall(function()
		dataStore:SetAsync("Player_"..player.UserId, data)
	end)
	
	if success then
		print("SAVED")
	else
		retryData(success, err, data, player)
		warn(err)
	end
end)

You could use ProfileService, it is very efficient to save and prevent data loss

1 Like

ProfileService vs DataStore2 vs Custom…
I have the most experience using DataStore2, does it really matter which one I choose? I’m talking about ProfileService & DataStore2.

I have no idea how the DataStore 2 works, well, if I have used it but I don’t know, it doesn’t seem convenient because I have to test the game several times in the studio and sometimes it doesn’t run. I decided to learn how to use the ProfileService since it saves in cache, and when you exit you will not have to make the data of the values ​​be collected, it will only take the cache and save it

1 Like

Just read up, it seems ProfileService is better. Anyways, I’ll check it out, thanks!

1 Like