DataStore function created to save data upon PlayerRemoving not executing fully

  1. What do I want to achieve?

I am in the process of creating a DataStore script to use and am currently working on the part that saves player data upon leaving, using the PlayerRemoving event.

  1. What is the issue?

I am not necessarily sure. After thorough testing, my script stops executing at random times. It seems almost as if the server is closing before the script has time to execute, but I do not see how that is possible. At no point of my testing phase has the following code ever thrown an error, it just stops executing at random places.

  1. What solutions have I tried thus far. Many iterations of the same thing pretty much. I also considered switching to a BindToCloseEvent, and though this still needs to be added, I feel that I still need a standard save upon leave feature.

Here is my code, it is quite short since I will not include the whole thing.

  • ServerScript: Currently only connects PlayerAdded/PlayerRemoving events.
Players.PlayerRemoving:Connect(function(player)
	DialogueModule.SavePlayerDataOnLeave(player)
end)

I will post snippets from the ModuleScript I am using to house my DataStore, only showing relevant functions.

  • Global Function that connects to the PlayerRemoving event: For the sake of simplicity, I am removing many of my debug attempts.
-- Global function meant to be connected to the PlayerRemoving event, saves data upon leaving.
function DSModule.SavePlayerDataOnLeave(player)
	local data, key = GetPlayerData(player)
	
	if data then
		local success, data = pcall(function()
			return dialogueDataStore:SetAsync(key, data)
		end)
		if success then
			if data ~= nil then
				print("data has been saved: " .. data) -- After numerous testing attempts, the script only made it to this line once.
			else
				print("Error: New data is nil")
			end
		else
			print("SetAsync() failed.") -- handle error where SetAsync() fails
		end
	else
		print("Something went wrong") -- handle this error
	end
end
  • The helper function the above chunk connects to:
local function GetPlayerData(player)
	local UserId = player.UserId
	local key = "User_" .. UserId .. "_Dialogue"
	
	local success, data = pcall(function()
		return dialogueDataStore:GetAsync(key)
	end)
	
	print(data)
	
	if success then
		return data, key
	else
		print("Data: " .. data)
		print("Key: " .. key)
		return nil, key -- using this nil value in the original function to handle errors the above function returned no data
	end
end

One other thing I have considered is scrapping the helper function entirely, and basically condensing these two functions into one.

Any help is appreciated, thanks in advance.

Hi there, what you have found is one of the most common ways players lose their data. I didn’t see anything completely wrong within your code, and from what I can tell, your assumption that the server is closing before the script fully executes is exactly what is going on.

This is because the :SetAsync() call yields, and does not complete before the server is ready to close. The server does not wait for the PlayerRemoving connection to finish. This problem really only occurs when the last player leaves a place, since the server will start shutting down right after (usually). You see it a lot when testing in Studio for that reason.

Here’s a forced example of this occurring:

local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("TestForDev")

game.Players.PlayerAdded:Connect(function(player)
	print(DataStore:GetAsync(player.UserId)) -- this just prints the value in datastore
end)

game.Players.PlayerRemoving:Connect(function(player)
	task.wait(5) -- this wait does not finish before the server closes
	DataStore:SetAsync(player.UserId, "YES") -- this line and below never runs
	print("Saved")
end)

If you were to run the above code in a script, it would never actually save any data since the server closes before the task.wait(5) finishes.


THE SOLUTION

You mentioned it within your post but utilizing game:BindToClose() would allow you to keep the game from closing until all the players data saves.

game:BindToClose() accepts a function as a parameter, and the game will not close until the function completely finishes, even if the function yields. (Note: BindToClose will only yield the server from closing for 30 seconds max)

All you would have to do is keep count of how many players are currently saving. Store that in a global variable that starts at 0. When the PlayerRemoving signal fires, add one to the “PlayerSaving” counter. Then when the saving finishes, remove one from the counter.

Within the function that is given as a parameter to game:BindToClose(), I would have a while loop that does task.wait() until “PlayerSaving” counter reaches 0.

If what I’m saying is confusing, here is the example from before with the BindToClose() safeguard that allows the game to save before closing, even with the task.wait()

local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("TestForDev")

local counter = 0 -- contains the amount of players saving

game.Players.PlayerAdded:Connect(function(player)
	print(DataStore:GetAsync(player.UserId)) -- this will now print something on second join
end)

game.Players.PlayerRemoving:Connect(function(player)
	counter += 1 -- lets the server know a player is saving
	task.wait(5)
	DataStore:SetAsync(player.UserId, "YES")
	print("Saved")
	counter -= 1 -- tells the server a player is done saving
end)

game:BindToClose(function()
	while counter > 0 do -- loop runs until all players have saved
		task.wait() -- yield keeps the server from closing
	end
end)

IMPORTANT: when you stop a game in Studio, BindToClose() will make studio freeze until the function passed to it finishes. Remember that the max time it will yield is 30 seconds, so even if it seems like studio crashed, WAIT! It will come back. This usually only happens when the counter was implemented wrong so the BindToClose() function never finishes.

You will have to figure out a way to use this in your own code yourself, but I think it would be easy to implement in your code. I would store the counter within your DSModule module script.

There are additional things to consider when making a save system, like what do you do if it fails vs if it succeeds, but this should solve the issue at hand.

Hope this was helpful, let me know if you need anythign else!

Thanks for the response. I came to the same conclusion myself, but I will still mark you as the solution. Since I made this post, I ended up reworking a lot of what I had thus far, so thanks for your insights. If you are offering to help, can I PM you with another part of the script and get your opinion on it? Thanks again.