Article
Duktape — embeddable, compact JavaScript engine
While large companies are in the race for performance of their JavaScript implementations, making them more complicated, there appeared something different: a compact embeddable JavaScript VM called Duktape.
Duktape is similar to Lua: it's a small, embeddable, and portable implementation of a high-level programming language, which you can use to add scripting to your C or C++ programs. Duktape consists of only two files:
duktape.c
and duktape.h
, which means that you don't have to use complicated processes to built library: just drop those files into your project.
Duckape is only 43K lines of code, but has full support for ECMAScript 5.1, and some features from ES6, has built-in regular expressions engine, Unicode support, plus some unique features: coroutines and CommonJS-like module loading.
Duktape also has a C API similar to Lua: you push, pop, and evaluate values in the context. For example, here's how to implement a C function callable from JavaScript, which returns a sum of arguments (example taken from Duktape website):
int adder(duk_context *ctx) {
int i;
int n = duk_get_top(ctx); /* #args */
double res = 0.0;
for (i = 0; i < n; i++) {
res += duk_to_number(ctx, i);
}
duk_push_number(ctx, res);
return 1; /* one return value */
}
Register it:
duk_push_global_object(ctx);
duk_push_c_function(ctx, adder, DUK_VARARGS);
duk_put_prop_string(ctx, -2 /*idx:global*/, "adder");
duk_pop(ctx); /* pop global */
and call:
duk_eval_string(ctx, "print('2+3=' + adder(2, 3));");
duk_pop(ctx); /* pop eval result */
Pretty much Lua-like. If you already know how to deal with Lua from C, Duktape feels like home!