Pcall throwing an error and aborting the script!

Reproduction Steps

Just to confirm, this is my current debug configuration in Studio:
vkfrgdgvGQ

Run this:

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

Expected Behavior

The script should not be aborted, since it’s wrapped in a pcall

Actual Behavior

vkfrgdgvGQ

But if I remove the argument 2 from getfenv:

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

… then pcall works:

vkfrgdgvGQ


Issue Area: Studio
Issue Type: Other
Impact: High
Frequency: Constantly

The call to setfenv you’re doing is not actually being called inside of pcall. It’s being called first, then the result is being passed as the first argument to pcall. The behavior is the same as if the code had been written like this:

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

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

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

pcall is a normal Lua function, so it can’t work in the way your example shows. It would have to be directly built into the language’s syntax, similar to if statements, or the try statements in other programming languages.

3 Likes