Quirrel4.41.0

types.Function.pcall

Method on every function
function.pcall(...): any

Calls the closure like call does, using env as its this and forwarding the rest of the arguments as its own parameters.

Parameters

...anythe first argument becomes this inside the call; the rest are forwarded as the closure's own arguments repeats

Return value

Whatever the call returns.

Errors

Whatever the call itself throws, propagated unchanged - a try/catch around pcall catches it the same as it would around call.

Notes

pcall never tail-calls, unlike call: every pcall keeps its own frame on the stack until the callee returns, so a deep chain of f.pcall(...) recursion exhausts the native call depth (Native stack overflow) much sooner than the same recursion written with call.

The two also differ once an error escapes uncaught: a host that installs a runtime error reporter (as the command-line tool does, to print a callstack) sees the callee's own frame for an unhandled error raised through call, but not through pcall - the report, if the host ever produces one, comes from whichever frame the error next escapes into. This has no effect on try/catch, which behaves identically either way.

Example

examples/types/function/pcall.nut
// the calling convention is identical to call: the first argument becomes
// 'this' inside the call
function greet(prefix) { return $"{prefix} {this.name}" }
println("greet.pcall({name = \"Bob\"}, \"Hi\") =", greet.pcall({name = "Bob"}, "Hi"))

// pcall never tail-calls, unlike call: a chain of pcall recursion runs out
// of native call depth long before an equivalent call-based one would
function loopy(n) {
    if (n <= 0)
        return "done"
    return loopy.pcall(this, n - 1)
}
try { println("loopy(60) =", loopy(60)) } catch(e) { println("loopy(60) throws:", e) }
Output:
greet.pcall({name = "Bob"}, "Hi") = Hi Bob
loopy(60) throws: Native stack overflow

See also

callCalls the closure, using env as its this and forwarding the rest of the arguments as its own parameters.
pacallCalls the closure like acall does, taking this and the arguments from an array: args[0] becomes this, and the rest of args becomes the closure's own parameters.
functionclass index