I'm trying to make my data saves safer so I went the wiki specifically this page: http://wiki.roblox.com/index.php?title=Saving_Player_Data
at the end, it mentions this
local function dataStoreRetry(dataStoreFunction) local tries = 0 local success = true local data = nil repeat tries = tries + 1 success = pcall(function() data = dataStoreFunction() end) if not success then wait(1) end until tries == DATASTORE_RETRIES or success if not success then error('Could not access DataStore! Warn players that their data might not get saved!') end return success, data end
do you see the dataStoreFunction() part well if it's a function then how come it's not in the rest of the tutorial if it's not a function then what does it do? Because they didn't mention this in any previous text or in a script part, I'm really frustrated. If the wiki can't say anything then what do I do if it's a success?
If you look closer, dataStoreFunction
actually is defined within the scope of the function. It's a parameter passed to the function:
local function dataStoreRetry(dataStoreFunction)
dataStoreRetry
is called within two wrapper functions defined at the bottom of the script:
... local function getPlayerData(player) return dataStoreRetry(function() return playerData:GetAsync(player.UserId) end) end local function savePlayerData(player) return dataStoreRetry(function() return playerData:SetAsync(player.UserId, sessionData[player]) end) end
Notice that when dataStoreRetry
is called, anonymous functions are being passed in as the arguments. This means that when dataStoreRetry
(the code in your question) runs, dataStoreFunction
is equal to whichever anonymous function was passed in.
For example, let's say that we called getPlayerData(player)
, which then calls dataStoreRetry
with the this as the dataStoreFunction
argument:
function() return playerData:GetAsync(player.UserId) end
You could substitute that function in for dataStoreFunction
, so your code above would look like this:
local function dataStoreRetry() local tries = 0 local success = true local data = nil local function dataStoreFunction() return playerData:GetAsync(player.UserId) end repeat tries = tries + 1 success = pcall(function() data = dataStoreFunction() end) if not success then wait(1) end until tries == DATASTORE_RETRIES or success if not success then error('Could not access DataStore! Warn players that their data might not get saved!') end return success, data end
The reason for doing this is so they can use the same dataStoreRetry
function to retry two different actions: GetAsync
and SetAsync
. All without having to rewrite the retry code for each action!
I know it's a lot, and requires a solid understanding of how functions can be used in Lua, but this is my best answer!