name: duk_pcall proto: | duk_int_t duk_pcall(duk_context *ctx, duk_idx_t nargs); stack: | [ ... func! arg1! ...! argN! ] -> [ ... retval! ] (if success, return value == 0) [ ... func! arg1! ...! argN! ] -> [ ... err! ] (if failure, return value != 0) summary: |

Call target function func with nargs arguments (not counting the function itself). The function and its arguments are replaced by a single return value or a single error value. An error thrown during the function call is caught.

The return value is:

Unlike most Duktape API calls, this call returns zero on success. This allows multiple error codes to be defined later.

Error objects caught are typically instances of Error and have useful properties like .stack, .fileName, and .lineNumber. These can be accessed using the normal property methods. However, arbitrary values can be thrown so you should avoid assuming that's always the case.

The target function this binding is initially set to undefined. If the target function is not strict, the binding is replaced by the global object before the function is invoked; see Entering Function Code. If you want to control the this binding, you can use duk_pcall_method() or duk_pcall_prop() instead.

example: | /* Assume target function is already on stack at func_idx; the target * function adds arguments and returns the result. */ duk_idx_t func_idx; duk_int_t rc; /* Basic example: function call and duk_safe_to_string() error print. */ duk_dup(ctx, func_idx); duk_push_int(ctx, 2); duk_push_int(ctx, 3); rc = duk_pcall(ctx, 2); /* [ ... func 2 3 ] -> [ 5 ] */ if (rc == DUK_EXEC_SUCCESS) { printf("2+3=%ld\n", (long) duk_get_int(ctx, -1)); } else { /* Coercing with duk_safe_to_string() is a useful default, but you can * also look up e.g. the .stack property of the error. */ printf("error: %s\n", duk_safe_to_string(ctx, -1)); } duk_pop(ctx); /* Accessing .stack to print a stack trace if the value caught is an * Error instance. */ duk_dup(ctx, func_idx); duk_push_int(ctx, 2); duk_push_int(ctx, 3); rc = duk_pcall(ctx, 2); /* [ ... func 2 3 ] -> [ 5 ] */ if (rc == DUK_EXEC_SUCCESS) { printf("2+3=%ld\n", (long) duk_get_int(ctx, -1)); } else { if (duk_is_error(ctx, -1)) { /* Accessing .stack might cause an error to be thrown, so wrap this * access in a duk_safe_call() if it matters. */ duk_get_prop_string(ctx, -1, "stack"); printf("error: %s\n", duk_safe_to_string(ctx, -1)); duk_pop(ctx); } else { /* Non-Error value, coerce safely to string. */ printf("error: %s\n", duk_safe_to_string(ctx, -1)); } } duk_pop(ctx); tags: - call - protected seealso: - duk_pcall_method - duk_pcall_prop introduced: 1.0.0