Hi, in some scripts I have seen this:
local success, err = pcall(function()
--code
end)
What does this do exactly?
Hi, in some scripts I have seen this:
local success, err = pcall(function()
--code
end)
What does this do exactly?
pcall stands for protected call. It calls a function. If the function errors, it will tell you the error instead of your whole script shutting down from the error. Don’t use it unless you need it, it’s bad practice.
The first thing it returns is success
. If success
is false, the second thing it returns is the error.
If success
is true, it returns whatever the function returned.
local success, result = pcall(function() game.Workspace:HeckingDestroyIt() end)
print(success) --> false
print(result) --> HeckingDestroyIt is not a valid member of Workspace
local success, result1, result2 = pcall(function() return "this function can", "return two things" end)
print(success) --> true
print(result1) --> this function can
print(result2) --> return two things
People tend to use it with ‘anonymous functions’, the (function() end)
syntax, but you can also call it with regular functions and pass in parameters.
local function AddTwoNumbers(num1, num2)
return num1 + num2
end
local success, result = pcall(AddTwoNumbers, 10, 20)
print(success, result) --> true 30
You really only need it when an error is out of your control. Some built-in Roblox functions have a chance to cause an error, such as DataStore requests and HttpService stuff.
local success, data = pcall(datastore.GetAsync, datastore, "data key")
if success then
-- do stuff with data
else
-- data didn't load, maybe warn someone and initialize empty data
end
Thanks bro i might use that for some data store stuff
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.