Im trying to mess with data stores, and as im referencing the API site, they said to "wrap your function call with a pcall." I understand the purpose, not the implementation.
local DataStoreService = game:GetService("DataStoreService") local experienceStore = DataStoreService:GetDataStore("PlayerExperience") **local success, err = pcall**(function() experienceStore:SetAsync("Player_1234", 50) end) if success then print("Success!") end
See, WHAT WOULD BE the bold part is what i dont understad. they make a variable, then another that equals pcall? wtf is pcall? why cant i find any documentation on how to use it? how is it connected to the function? HOW IS IT EVEN ALLOWED TO WEDGE ITSELF BETWEEN THE FUNCTION NAME AND THE FUNCTION??
I would just copy paste the code and be done with it, but im trying to implement it into a server-invoke call. So it looks dicey as is;
InventoryFunction.OnServerInvoke= function (playerID,Intent, number) if Intent == "read" then return Inventory:GetAsync(playerID) else if Intent == "increment" then Inventory:IncrementAsync(playerID, number) end end end
That works, i know it, but how can i add a pcall to catch data-store problems?
A pcall function is a way to encapsulate your code so you can catch and handle errors. The first argument, in our case the function, runs in a protected mode which essentially says that if there are no errors, the pcall will return true. If there is an error it'll return false plus the error message.
In your usecase with datastores, wrapping your function in a pcall is a good way to see if SetAsync was succesful or not. Sometimes Roblox datastore's can go down and if this was the case it would shoot back that success is equal to false and you could handle it from there (tell the player, kick them, etc).
Usecase 1:
local wasSuccess, didError = pcall(function() print("Hello world!") end) print(wasSuccess, didError) -- Output: -- true, nil
Usecase 2:
local wasSuccess, didError = pcall(function() error("Uh oh, something went wrong!") end) print(wasSuccess, didError) -- Output: -- false, ServerScriptService.Script:2: Uh oh, something went wrong!