Download the source distributable from the Download page.
Unpack the distributable:
$ cd /tmp $ tar xvfJ duktape-<version>.tar.xz
Compile the command line tool using the provided Makefile:
$ cd /tmp/duktape-<version>/ $ make -f Makefile.cmdline
gcc
installed. If you don't,
you can just edit the Makefile to match your compiler (the Makefile is
quite simple).
readline
and the necessary development headers,
you can enable line editing support by editing the Makefile:
-DDUK_CMDLINE_FANCY
-lreadline
and -lncurses
You can now run Ecmascript code interactively:
$ ./duk ((o) Duktape [no readline] 1.1.0 (v1.1.0) duk> print('Hello world!') Hello world! = undefined
You can also run Ecmascript code from a file which is useful for playing with
features and algorithms. As an example, create fib.js
:
Test the script from the command line:
$ ./duk fib.js 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
The command line tool is simply an example of a program which embeds
Duktape. Embedding Duktape into your program is very simple: just add
duktape.c
and duktape.h
to your build, and call the
Duktape API from elsewhere in your program.
The distributable contains a very simple example program, hello.c
,
which illustrates this process. Compile the test program e.g. as (see
Compiling for compiler option suggestions):
$ cd /tmp/duktape-<version>/ $ gcc -std=c99 -o hello -Isrc/ src/duktape.c examples/hello/hello.c -lm
The test program creates a Duktape context and uses it to run some Ecmascript code:
$ ./hello Hello world! 2+3=5
Because Duktape is an embeddable engine, you don't need to change the basic control flow of your program. The basic approach is:
Let's look at a simple example program. The program reads in a line from
stdin
using a C mainloop, calls an Ecmascript helper to transform
the line, and prints out the result. The line processing function can take
advantage of Ecmascript goodies like regular expressions, and can be easily
modified without recompiling the C program.
The script code will be placed in process.js
. The example
line processing function converts a plain text line into HTML, and
automatically bolds text between stars:
The C code, processlines.c
initializes a Duktape context,
evaluates the script, then proceeds to process lines from stdin
,
calling processLine()
for every line:
Let's look at the Duktape specific parts of the example code piece by piece. Here we need to gloss over some details for brevity, see Programming model for a detailed discussion:
ctx = duk_create_heap_default(); if (!ctx) { printf("Failed to create a Duktape heap.\n"); exit(1); }
First we create a Duktape context. A context allows us to exchange values with Ecmascript code by pushing and popping values to the value stack. Most calls in the Duktape API operate with the value stack, pushing, popping, and examining values on the stack. For production code you should use duk_create_heap() so that you can set a fatal error handler. See Error handling for discussion of error handling best practices.
if (duk_peval_file(ctx, "process.js") != 0) { printf("Error: %s\n", duk_safe_to_string(ctx, -1)); goto finished; } duk_pop(ctx); /* ignore result */
The eval call reads in process.js
, then compiles and executes
the script. The script registers processLine()
into the Ecmascript
global object for later use. The eval call is protected so that any script
errors, such as syntax errors, are caught and handled without causing a fatal
error. If an error occurs, the error message is coerced safely using
duk_safe_to_string() which is
guaranteed not to throw a further error. The result of the string coercion is
a const char *
pointing to a read-only, NUL-terminated, UTF-8
encoded string, which can be used directly with printf
.
duk_push_global_object(ctx); duk_get_prop_string(ctx, -1 /*index*/, "processLine");
The first call pushes the Ecmascript global object to the value stack.
The second call looks up processLine
property of the global object
(which the script in process.js
has defined). The -1
argument is an index to the value stack; negative values refer to stack
elements starting from the top, so -1
refers to the topmost
element of the stack, the global object.
duk_push_string(ctx, line);
Pushes the string pointed to by line
to the value stack. The
string length is automatically determined by scanning for a NUL terminator
(same as strlen()
). Duktape makes a copy of the string when it is
pushed to the stack, so the line
buffer can be freely modified when
the call returns.
if (duk_pcall(ctx, 1 /*nargs*/) != 0) { printf("Error: %s\n", duk_safe_to_string(ctx, -1)); } else { printf("%s\n", duk_safe_to_string(ctx, -1)); } duk_pop(ctx); /* pop result/error */
At this point the value stack contains: the global object, the processLine
function, and the line
string. The
duk_pcall() method calls a function with a
specified number of arguments given on the value stack, and replaces both the
function and the argument values with the function's return value.
Here the resulting value stack contains: the global object and the call result.
The call is protected so that errors can be caught and printed. The
duk_safe_to_string() API call is
again used to print errors safely. Finally, the result (or error) is popped
off the value stack.
duk_destroy_heap(ctx);
Destroy the Duktape context, freeing all resources held by the context. This call will free the value stack and all references on the value stack. In our example we left the global object on the value stack on purpose. This is not a problem: no memory leaks will occur even if the value stack is not empty when the heap is destroyed.
Compile like above:
$ gcc -std=c99 -o processlines -Isrc/ src/duktape.c processlines.c -lm
Test run (ensure that process.js
is in the current directory):
$ echo "I like *Sam & Max*." | ./processlines I like <b>Sam & Max</b>.
The integration example illustrated how C code can call into Ecmascript to do things which are easy in Ecmascript but difficult in C.
Ecmascript also often needs to call into C when the situation is reversed. For instance, while scripting is useful for many things, it is not optimal for low level byte or character processing. Being able to call optimized C helpers allows you to write most of your script logic in nice Ecmascript but call into C for the performance critical parts. Another reason for using native functions is to provide access to native libraries.
To implement a native function you write an ordinary C function which conforms to a special calling convention, the Duktape/C binding. Duktape/C functions take a single argument, a Duktape context, and return a single value indicating either error or number of return values. The function accesses call arguments and places return values through the Duktape context's value stack, manipulated with the Duktape API. We'll go deeper into Duktape/C binding and the Duktape API later on. Example:
duk_ret_t my_native_func(duk_context *ctx) { double arg = duk_require_number(ctx, 0 /*index*/); duk_push_number(ctx, arg * arg); return 1; }
Let's look at this example line by line:
double arg = duk_require_number(ctx, 0 /*index*/);
Check that the number at value stack index 0 (bottom of the stack, first
argument to function call) is a number; if not, throws an error and never
returns. If the value is a number, return it as a double
.
duk_push_number(ctx, arg * arg);
Compute square of argument and push it to the value stack.
return 1;
Return from the function call, indicating that there is a (single) return
value on top of the value stack. You could also return 0
to indicate
that no return value is given (in which case Duktape defaults to Ecmascript
undefined
). A negative return value which causes an error to be
automatically thrown: this is a shorthand for throwing errors conveniently.
Note that you don't need to pop any values off the stack, Duktape will do that
for you automatically when the function returns.
See Programming model for more details.
We'll use a primality test as an example for using native code to speed up Ecmascript algorithms. More specifically, our test program searches for primes under 1000000 which end with the digits '9999'. The Ecmascript version of the program is:
Note that the program uses the native helper if it's available but falls back to an Ecmascript version if it's not. This allows the Ecmascript code to be used in other containing programs. Also, if the prime check program is ported to another platform where the native version does not compile without changes, the program remains functional (though slower) until the helper is ported. In this case the native helper detection happens when the script is loaded. You can also detect it when the code is actually called which is more flexible.
A native helper with functionality equivalent to primeCheckEcmascript
is quite straightforward to implement. Adding a program main we get
primecheck.c
:
The new calls here are, line by line:
int val = duk_require_int(ctx, 0); int lim = duk_require_int(ctx, 1);
These two calls check the two argument values given to the native helper.
If the values are not of the Ecmascript number type, an error is thrown.
If they are numbers, their value is converted to an integer and assigned to
the val
and lim
locals. The index 0 refers to the first
function argument and index 1 to the second.
Technically duk_require_int()
returns a duk_int_t
; this
indirect type is always mapped to an int
except on obscure platforms
where an int
is only 16 bits wide. In ordinary application code you
don't need to worry about this, see C types for more discussion.
duk_push_false(ctx); return 1;
Pushes an Ecmascript false
to the value stack. The C return value
1 indicates that the false
value is returned to the Ecmascript caller.
duk_push_global_object(ctx); duk_push_c_function(ctx, native_prime_check, 2 /*nargs*/); duk_put_prop_string(ctx, -2, "primeCheckNative");
The first call, like before, pushes the Ecmascript global object to the
value stack. The second call creates an Ecmascript Function
object
and pushes it to the value stack. The function object is bound to the
Duktape/C function native_prime_check
: when the Ecmascript function
created here is called from Ecmascript, the C function gets invoked.
The second argument (2
) to the call indicates how many arguments
the C function gets on the value stack. If the caller gives fewer arguments,
the missing arguments are padded with undefined
; if the caller gives
more arguments, the extra arguments are dropped automatically. Finally, the
third call registers the function object into the global object with the
name primeCheckNative
and pops the function value off the stack.
duk_get_prop_string(ctx, -1, "primeTest"); if (duk_pcall(ctx, 0) != 0) { printf("Error: %s\n", duk_safe_to_string(ctx, -1)); } duk_pop(ctx); /* ignore result */
When we come here the value stack already contains the global object
at the stack top. Line 1 looks up the primeTest
function
from the global object (which was defined by the loaded script). Lines
2-4 call the primeTest
function with zero arguments, and
prints out an error safely if one occurs. Line 5 pops the call result
off the stack; we don't need the return value here.
Compile like above:
$ gcc -std=c99 -o primecheck -Isrc/ src/duktape.c primecheck.c -lm
Test run (ensure that prime.js
is in the current directory):
$ time ./primecheck Have native helper: true 49999 59999 79999 139999 179999 199999 239999 289999 329999 379999 389999 409999 419999 529999 599999 619999 659999 679999 769999 799999 839999 989999 real 0m2.985s user 0m2.976s sys 0m0.000s
Because most execution time is spent in the prime check, the speed-up
compared to plain Ecmascript is significant. You can check this by editing
prime.js
and disabling the use of the native helper:
// Select available helper at load time var primeCheckHelper = primeCheckEcmascript;
Re-compiling and re-running the test:
$ time ./primecheck Have native helper: false 49999 59999 79999 139999 179999 199999 239999 289999 329999 379999 389999 409999 419999 529999 599999 619999 659999 679999 769999 799999 839999 989999 real 0m23.609s user 0m23.573s sys 0m0.000s