Why is pcall aborting the script with an error?

I want to get environment variables at stack level 2.
For that, I use getfenv(2).
But apparently, there is no way to know if getfenv will give an error if this stack level does not exist.
For that, I put it inside a pcall.

pcall(getfenv(2))

But to my surprise, the script is aborting and showing an error EVEN WITH PCALL.
Isn’t it the job of pcall to intercept errors and PREVENT THE SCRIPT FROM BEING ABORTED?

image

1 Like

I discovered.
It’s because I had configured my Studio to stop with “On All Exceptions” errors:
image

Changing to “On Unhandled Exceptions” it solved the problem.

No…
It’s not working:

local Sucess, Error = pcall(getfenv(2).script)
print("Sucess, Error: ", Sucess, Error)

image


However, this works:

local status, err = pcall(function () error({code=121}) end)
print(err.code)  -->  121

image

What’s wrong?

You can close this topic now because in bug reports an admin already said why it behaves like that. For anybody wondering why, the arguments get calculated before it actually goes through the protected call. So to fix it you should wrap it all in a function like this: local Success, Error = pcall(function() return getfenv(2).script end)

2 Likes

Here’s the solution:

local s, r = pcall(getfenv, 2)
print(s, r) --true, table...

You’re calling getfenv and passing its result to pcall, instead you should pass a reference to getfenv to pcall, any additionaly arguments to pcall will be passed to the referenced function.

Instead, you should wrap the thing you’re trying to run inside of a function, like this:

The creation of a new lambda (anonymous) function isn’t necessary.

2 Likes