So, I've been pcalling GetAsync
and SetAsync
but I'm not sure if I'm creating the right backup plan:
local DSS = game:GetService("DataStoreService") local exampleDataStore = DSS:GetDataStore("Example1") local function saveData(Player) -- pretend i got the player local suc, err = pcall(function() local emptyTable = {} -- pretend there is data here DSS:SetAsync(Player.UserId, emptyTable) end) if not suc then print(err) repeat wait() suc, err = pcall(function() local emptyTable = {} -- pretend there is data here DSS:SetAsync(Player.UserId, emptyTable) end) until suc do end end end
so I'm wondering if i'm doing this correctly to secure the player data using pcall. Any tips or feedback on more efficient coding or better methods will be appreciated.
Edit: Some people have told me I'm doing it wrong
You're checking for the wrong success variable. you are in scope of the first suc variable meaning you are checking if the first success variable is true, which, if you error it will never be and you'll be stuck in an infinite loop forever. You instead want to be checking if the second success variable is true/false.
another thing that might end up looping forever is if we can't save the data. set a maximum amount of tries like in the example below so that doesn't become an issue.
Another thing, is you are asking the Datastore Service to use SetAsync() where you want to have the exampleDataStore use SetAync()
We also want to save the player's data, not an empty table, so I included a place to store all of the player's in game's data so you can access it when you want to save to datastore.
Not required, but you can use a module script so you can save / get the data from any script.
lastly, i'd suggest u using updateasync() over setasync() as setasync might not be the most recent data causing data loss.
i wrote about update async here
and i got the idea of using update async like that from here:
-- this is a table containing the in game data --you can access the player's data by saying AllPlayerData[playerNameGoesHere] (in english, AllPlayerData AT playerNameGoesHere) AllPlayerData = { [playerNameGoesHere] = {} } local DSS = game:GetService("DataStoreService") local exampleDataStore = DSS:GetDataStore("Example1") local function saveData(player) local success = nil --the player has data, attempt to save that data success , err = pcall(function() exampleDataStore:SetAsync(player.UserId, AllPlayerData[player.Name]) end) --setasync() failed, attempt three more times until we save successfully or go over our attempt limit if not success then local attempts = 0 print(err) while(not success or attempts < 3)do wait(3) success, err = pcall(function() exampleDataStore:SetAsync(player.UserId, AllPlayerData[player.Name]) end) attempts = attempts + 1 end end end