mirror of https://github.com/svaarala/duktape.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
2.7 KiB
75 lines
2.7 KiB
name: duk_push_c_function
|
|
|
|
proto: |
|
|
duk_idx_t duk_push_c_function(duk_context *ctx, duk_c_function func, duk_idx_t nargs);
|
|
|
|
stack: |
|
|
[ ... ] -> [ ... func! ]
|
|
|
|
summary: |
|
|
<p>Push a new function object, associated with a C function, to the stack.
|
|
The function object is an ECMAScript function object; when called, <code>func</code>
|
|
will be called using the Duktape/C function interface. Returns non-negative index
|
|
(relative to stack bottom) of the pushed function.</p>
|
|
|
|
<p>The <code>nargs</code> argument controls how the value stack looks like when
|
|
<code>func</code> is entered:</p>
|
|
|
|
<ul>
|
|
<li>If <code>nargs</code> is >= 0, it indicates the exact number of arguments the
|
|
function expects to see; extra arguments are discarded and missing arguments
|
|
are filled in with <code>undefined</code> values. Upon entry to the function, value
|
|
stack top will always match <code>nargs</code>.</li>
|
|
<li>If <code>nargs</code> is set to <code>DUK_VARARGS</code>, the value stack will contain
|
|
actual (variable) call arguments and the function needs to check actual argument
|
|
count with <code><a href="#duk_get_top">duk_get_top()</a></code>.</li>
|
|
</ul>
|
|
|
|
<p>The function created will be callable both as a normal function (<code>func()</code>)
|
|
and as a constructor (<code>new func()</code>). You can differentiate between the two
|
|
call styles using <code><a href="#duk_is_constructor_call">duk_is_constructor_call()</a></code>.
|
|
Although the function can be used as a constructor, it doesn't have an automatic
|
|
<code>prototype</code> property like ECMAScript functions.</p>
|
|
|
|
<div class="note">
|
|
If you intend to use the pushed function as a constructor, you should usually
|
|
create a prototype object and set the <code>prototype</code> property of the
|
|
function manually.
|
|
</div>
|
|
|
|
example: |
|
|
duk_ret_t my_addtwo(duk_context *ctx) {
|
|
double a, b;
|
|
|
|
/* Here one can expect that duk_get_top(ctx) == 2, because nargs
|
|
* for duk_push_c_function() is 2.
|
|
*/
|
|
|
|
a = duk_get_number(ctx, 0);
|
|
b = duk_get_number(ctx, 1);
|
|
duk_push_number(ctx, a + b);
|
|
return 1; /* 1 = return value at top
|
|
* 0 = return 'undefined'
|
|
* <0 = throw error (use DUK_RET_xxx constants)
|
|
*/
|
|
}
|
|
|
|
void test(void) {
|
|
duk_idx_t func_idx;
|
|
|
|
func_idx = duk_push_c_function(ctx, my_addtwo, 2);
|
|
duk_push_int(ctx, 2);
|
|
duk_push_int(ctx, 3); /* -> [ ... func 2 3 ] */
|
|
duk_call(ctx, 2); /* -> [ ... res ] */
|
|
printf("2+3 is %ld\n", (long) duk_get_int(ctx, -1));
|
|
duk_pop(ctx);
|
|
}
|
|
|
|
tags:
|
|
- stack
|
|
- function
|
|
|
|
seealso:
|
|
- duk_push_c_lightfunc
|
|
|
|
introduced: 1.0.0
|
|
|