So I have been seeing lots of dev forums and use in games of the Pcall function. I have searched all over the forum and I am still confused about what the use of Pcall is. Can someone explain to me in a bit of depth what the use is and possibly provide me with an example of how to use it or what it is doing? Thanks!
pcall is basically a function that returns 2 things. success and error. It would be something like this
local success, err = pcall(function()
end)
if not success then
warn(err)
end
pcall is used to know if a function breaks or not, and also so that scripts do not break, when using it it returns 1 or 2 values depending on whether it was broken or not.
local Success, Err = pcall(function()
-- Code
end)
if it works: true, nil
if not working: false, error found
Also, if inside it has a return, Err will be that value if Success is true.
local Success, Result = pcall(function()
return "Hi " + 5
end)
print(Success, Result) -- false, attempt to perform arithmetic (add) on string and number
local Success, Result = pcall(function()
return "Hi " .. 5
end)
print(Success, Result) -- true, "Hi 5"
https://www.lua.org/pil/8.4.html
This is the official lua page on pcall. It should help you to understand pcalls.
They avoid the entire script to be confused and throw errors. Instead, you can, with pcall, catch errors (of they are) before they are thrown up.
It is mainly used in Robux transactions in games, Datastores and can be used in many more ways