What does a pcall actually return?

I know that a pcall returns two values, that’s why you do stuff like:

local success, errormessage = pcall(function()

But what are these values?
You can do stuff like

if success then

So are they boolvalues? What do they exactly tell you? Pcalls actually confuse me because of that a bit.

1 Like

Well the first value it returns is the success value, it returns if the script successfully runs without errors, the second one catches the errors and then returns the error inside the script.

8 Likes

Alright, I understood the first value but the second one I didn’t. What do you mean with catches the errors and then returns the error inside the script?

Errormsg will be a string value

1 Like

It returns a string of the error I believe.

1 Like

Exactly. The second one is the string value that resembles the error that was caught by the pcall.

3 Likes

A pcall asserts one output. If it errors, it will return an error message as second output. First variable output is always a boolean.

4 Likes

And if you want it to do a callback instead of just returning the string of the error you can use xpcall. Which is practically the same thing except that you can add a function to callback if the script errors.

2 Likes

So even though it errors, the script will just continue?

It doesn’t stop the rest of the script outside of the pcall.

3 Likes

Yep, that’s exactly why we use pcall

1 Like

The results of pcall are, if the function errors, false and the error object (could be anything); otherwise, the results are true and all of the return values from the function.

local function f(err,value)
    if err then
        error(value)
    else
        return value
    end
end
local success,result = pcall(f,true,"abc")
print(success,result) --> false  <script>:3: abc
local success,result = pcall(f,false,"def")
print(success,result) --> true  def
2 Likes

if the code was not executed without errors, then the first variable will return false

  local success = pcall(function()
        return nil* "string"  
  end)
  
  if not success then print("there was an error")  end 
  --> prints, because success was not equal to true

Now to catch the reason an error occurred, use a second variable

 local success, err = pcall(function()
     print(nil + 5)  
 end)
 
 if not success then
     return warn(err)
 end
 --// warns this in the output:
 -->  18:13:14.252 -  :2:  attempt to perform arithmetic (add) on nil and number
4 Likes