How do functions return twice?

So I was thinking about pcall and error. How does error return from pcall?

for those replying to return multiple values, that’s not what I’m asking

local function fun()
    local function endIt()
         return return; --This is basically what I'm asking
    end
    endIt()
end

pcall does not continue the thread after error, so how does it end it there?

Can you clarify what you mean? Do you mean how does pcall return multiple values, or do you mean how does pcall return what you return within the interior function?

Just return multiple values:

function return_values()
   return 1, 2, 3, 4, 5
end

print(return_values())

When a function returns it can return 2 or more values. For instance:

function hello()
	return 1, 2, 3
end

local a, b, c = hello()

In this example the variable a gets a value of 1 and so on. This is what is known as multi-assignment (assigning multiple values to multiple variables in the same assignment expression).

local Success, Error = pcall(function()
	
end)

if not Success then
	print(Error)
end

?

basically

Because pcall is a function built in to luau, and pcall is the only method we can use to check errors it’s a bit difficult to explain using luau code. But I’ll try my best.

local function pcall(func)
	local success = math.random() < 0.5 and true or false
	
	if success then
		return true, func()
		
	else
		return false, "Example error message"
	end
end

In this example, success is random, but imagine it wasn’t. Also the only error message available is “Example error message”, but suppose that was whatever error message the pcall encountered. Here you can see how you can return multiple variables, and depending on the success of a condition, return differing values depending on whether the condition was successful or not.

Also, by calling func() we can return the values from the interior function passed as an argument to pcall.

1 Like

But how does it stop at error and return it? error is a function, simply returning from that would continue the thread

pcall is built into luau. Luau is built in c++, and as a result, it likely makes use of a try-catch block (in c++) to call the function. If the function passes, then it can return as normal. If the function fails, it instead goes to a catch block and gives you the error.

While error may be a function, it causes a stop in the execution of a thread because a problem occurred. Pcall preserves the execution of the main thread by catching any errors that occurred and moving on to the rest of your code execution.

3 Likes