What does pcall do?

As the title suggests what does pcall do? Specifically for Datastores and how is it used and what are some Examples?

4 Likes
4 Likes

A pcall can catch errors in scripts when using something that ends in Async.

You can see if it fails or succeeds.

Seriously, next time consider searching it up on google, but Pcalls are used to catch errors in scenarios that are game-breaking or can’t be relied on. But try to use them minimally; they are not performant.

2 Likes

Game breaking: agreed, I use it not just for network calls like datastores but also a round based game when main script is manipulating players who might come go drop tablet in a swimming pool etc. As a protection to keep the Rounds running with an emergency cleanup if not successful. I find pcall effective.

1 Like

Simple untested set up

local DataStoreService = game:GetService("DataStoreService")
local cashDataStore = DataStoreService:GetDataStore("CashDataStore")

local function saveCash(player, cash)
    pcall(function()
        cashDataStore:SetAsync(player.UserId, cash)
    end)
end

local function loadCash(player)
    local success, cash = pcall(function()
        return cashDataStore:GetAsync(player.UserId)
    end)
    if success then
        return cash or 0
    else
        return 0
    end
end

The pcall loads the data of the player. If there is an error pcall will not stop the script and return 0.
If there is not an error it will load the data. If no data it will return 0. If there is it will return the amount.

1 Like

Wdym?
Are they bad for peformance?

Yes because they have to catch errors…

Pcall can catch errors, and run functions in the case of an error, this can prevent the entire function / thread its being ran from being stopped in a error.
And yes they might be a tiny bit peformance heavy, because it catches errors.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.