- 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.
- 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.
- 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.