What is pcall()?

Someone explain this pcall() thing for me? I’m having a hard time understanding this one.

https://www.lua.org/pil/8.4.html

Search first before making posts, please.

It’s a way of handling outcomes of functions. Think of it like a protection check. So you could run a fiction if it fails you could run it again or different logic.

There are a few call types like that, but pcall is common.

It’s easily overused though and you should use it sparingly as you can accidently obscure bad code by error wrapping everything with it

5 Likes

You can get response or error from the called function in pcall without script stop.

2 Likes

Usually when errors happen in a script, the script is stopped at that line. When you use a pcall, the script will resume even if there is an error.

An example of where a pcall would be useful could be when you are getting someone’s data from a datastore, if the data is nil, or the data fails to load, we don’t want to stop the script, so we would use a pcall to load the data.

local Data
local Success, ErrorStatement = pcall(function()
     Data = DS:GetAsync("Key")
end))
14 Likes

You should check out this post by @ReturnedTrue

Pcalls - When and how to use them

1 Like