Duktape built-ins

This section describes Duktape-specific built-in objects, methods, and values.

Additional global object properties

PropertyDescription
DuktapeThe Duktape built-in object. Contains miscellaneous implementation specific stuff.
ProxyProxy constructor borrowed from ES6 draft (not part of Ecmascript E5/E5.1).
printNon-standard, browser-like function for writing to stdout.
alertNon-standard, browser-like function for writing to stderr.

print and alert

print() writes to stdout with an automatic flush afterwards. The bytes written depend on the arguments:

alert() behaves the same way, but writes to stderr. Unlike a browser alert(), the call does not block.

The Duktape object

PropertyDescription
versionDuktape version number: (major * 10000) + (minor * 100) + patch.
envCryptic, version dependent summary of most important effective options like endianness and architecture.
finSet or get finalizer of an object.
encEncode a value (hex, base-64, JX, JC): Duktape.enc('hex', 'foo').
decDecode a value (hex, base-64, JX, JC): Duktape.dec('base64', 'Zm9v').
infoGet internal information (such as heap address and alloc size) of a value in a version specific format.
lineGet current line number.
actGet information about call stack entry.
gcTrigger mark-and-sweep garbage collection.
compactCompact the memory allocated for a value (object).
errCreateCallback to modify/replace a created error.
errThrowCallback to modify/replace an error about to be thrown.
BufferBuffer constructor (function).
PointerPointer constructor (function).
ThreadThread constructor (function).
LoggerLogger constructor (function).

version

The version property allows version-based feature detection and behavior. Version numbers can be compared directly: a logically higher version will also be numerically higher. For example:

if (typeof Duktape !== 'object') {
    print('not Duktape');
} else if (Duktape.version >= 10203) {
    print('Duktape 1.2.3 or higher');
} else if (Duktape.version >= 800) {
    print('Duktape 0.8.0 or higher (but lower than 1.2.3)');
} else {
    print('Duktape lower than 0.8.0');
}

Unofficial development snapshots have patch level set to 99. For example, version 0.11.99 (1199) would be a development snapshot after 0.11.0 but before the next official release.

Remember to check for existence of Duktape when doing feature detection. Your code should typically work on as many engines as possible. Avoid the common pitfall of using a direct identifier reference in the check:

// Bad idea: ReferenceError if missing
if (!Duktape) {
    print('not Duktape');
}

// Better: check through 'this' (bound to global)
if (!this.Duktape) {
    print('not Duktape');
}

// Better: use typeof to check also type explicitly
if (typeof Duktape !== 'object') {
    print('not Duktape');
}

env

env summarizes the most important effective compile options in a version specific, quite cryptic manner. The format is version specific and is not intended to be parsed programmatically. This is mostly useful for developers (see duk_hthread_builtins.c for the code which sets the value).

Example from Duktape 0.10.0:

ll u p2 a4 x64     // l|b|m integer endianness, l|b|m double endianness,
                   // p|u packed/unpacked tval, p1|p2 prop memory layout,
                   // a1/a4/a8 align target, arch

fin()

When called with a single argument, gets the current finalizer of an object:

var currFin = Duktape.fin(o);

When called with two arguments, sets the finalizer of an object (returns undefined):

Duktape.fin(o, function(x) { print('finalizer called'); });
Duktape.fin(o, undefined);  // disable

enc()

enc() encodes its argument value into chosen format. The first argument is a format (currently supported are "hex", "base64", "jx" and "jc"), second argument is the value to encode, and any further arguments are format specific.

For "hex" and "base64", buffer values are encoded as is, other values are string coerced and the internal byte representation (extended UTF-8) is then encoded. The result is a string. For example, to encode a string into base64:

var result = Duktape.enc('base64', 'foo');
print(result);  // prints 'Zm9v'

For "jx" and "jc" the argument list following the format name is the same as for JSON.stringify(): value, replacer (optional), space (optional). For example:

var result = Duktape.enc('jx', { foo: 123 }, null, 4);
print(result);  // prints JX encoded {foo:123} with 4-space indent

dec()

dec() provides the reverse function of enc().

For "hex" and "base64" the input value is first string coerced (it only really makes sense to decode strings). The result is always a buffer. For example:

var result = Duktape.dec('base64', 'Zm9v');
print(typeof result, result);  // prints 'buffer foo'

If you wish to get back a string value, you can simply:

var result = String(Duktape.dec('base64', 'Zm9v'));
print(typeof result, result);  // prints 'string foo'

For "jx" and "jc" the argument list following the format name is the same as for JSON.parse(): text, reviver (optional). For example:

var result = Duktape.dec('jx', "{foo:123}");
print(result.foo);  // prints 123

info()

When given an arbitrary input value, Duktape.info() returns an array of values with internal information related to the value. The format of of the values in the array is version specific. This is mainly useful for debugging and diagnosis, e.g. when estimating rough memory usage of objects.

The current result array format is described in the table below. Notes:

Type0123456789
undefined type tag - - - - - - - - -
null type tag - - - - - - - - -
boolean type tag - - - - - - - - -
number type tag - - - - - - - - -
string type tag heap ptr refcount heap hdr size - - - - - -
object, Ecmascript function type tag heap ptr refcount heap hdr size prop alloc size prop entry count prop entry used prop array count prop hash count func data size
object, Duktape/C function type tag heap ptr refcount heap hdr size prop alloc size prop entry count prop entry used prop array count prop hash count -
object, thread type tag heap ptr refcount heap hdr size prop alloc size prop entry count prop entry used prop array count prop hash count -
object, other type tag heap ptr refcount heap hdr size prop alloc size prop entry count prop entry used prop array count prop hash count -
buffer, fixed type tag heap ptr refcount heap hdr size - - - - - -
buffer, dynamic type tag heap ptr refcount heap hdr size curr buf size - - - - -
pointer type tag - - - - - - - - -

line()

Get the line number of the call site. This may be useful for debugging, e.g.:

log.info('reached line:', Duktape.line());
As Duktape.act() provides more information, this function will probably be removed.

act()

Get information about a call stack entry. Takes a single number argument indicating depth in the call stack: -1 is the top entry, -2 is the one below that etc. Returns an object describing the call stack entry, or undefined if the entry doesn't exist. Example:

function dump() {
    var i, t;
    for (i = -1; ; i--) {
        t = Duktape.act(i);
        if (!t) { break; }
        print(i, t.lineNumber, t.function.name, Duktape.enc('jx', t));
    }
}

dump();

The example, when executed with the command line tool, currently prints something like:

-1 0 act {lineNumber:0,pc:0,function:{_func:true}}
-2 4 dump {lineNumber:4,pc:16,function:{_func:true}}
-3 10 global {lineNumber:10,pc:5,function:{_func:true}}

The interesting entries are lineNumber and function which provides e.g. the function name.

You can also implement a helper to get the current line number using Duktape.act():

function getCurrentLine() {
    // indices: -1 = Duktape.act, -2 = getCurrentLine, -3 = caller
    var a = Duktape.act(-3) || {};
    return a.lineNumber;
}
print('running on line:', getCurrentLine());
The properties provided for call stack entries may change between versions.

gc()

Trigger a forced mark-and-sweep collection. If mark-and-sweep is disabled, this call is a no-op.

compact()

Minimize the memory allocated for a target object. Same as the C API call duk_compact() but accessible from Ecmascript code. If called with a non-object argument, this call is a no-op. The argument value is returned by the function, which allows code such as:

var obj = {
    foo: Duktape.compact({ bar:123 })
}

This call is useful when you know that an object is unlikely to gain new properties, but you don't want to seal or freeze the object in case it does.

errCreate() and errThrow()

These can be set by user code to process/replace errors when they are created (errCreate) or thrown (errThrow). Both values are initially non-existent.

See Error handlers (errCreate and errThrow) for details.

Duktape.Buffer (constructor)

PropertyDescription
prototypePrototype for Buffer objects.

The Buffer constructor is a function which returns a plain buffer when called as a normal function and a Buffer object when called as a constructor. Otherwise the behavior is the same:

There is currently (in Duktape 0.10.0) no way direct way to create a copy of a buffer (i.e. a new buffer with the same contents but a separate underlying buffer). This will be added in Duktape 0.11.0; for now you can make a copy inefficiently e.g. as Duktape.Buffer(String(orig_buf)). Buffers are currently mostly intended to be operated with from C code.

Duktape.Buffer.prototype

PropertyDescription
toStringConvert Buffer to a printable string.
valueOfReturn the primitive buffer value held by Buffer.

toString() and valueOf accept both plain buffers and Buffer objects as their this binding. This allows code such as:

var plain_buf = Duktape.Buffer('test');
print(plain_buf.toString());

Duktape.Pointer (constructor)

PropertyDescription
prototypePrototype for Pointer objects.

The Pointer constructor is a function which can be called both as an ordinary function and as a constructor:

Duktape.Pointer.prototype

PropertyDescription
toStringConvert Pointer to a printable string.
valueOfReturn the primitive pointer value held by Pointer.

toString() and valueOf accept both plain pointers and Pointer objects as their this binding. This allows code such as:

var plain_ptr = Duktape.Pointer({ test: 'object' });
print(plain_ptr.toString());

Duktape.Thread (constructor)

PropertyDescription
prototypePrototype for Thread objects.
resumeResume target thread with a value or an error. Arguments: target thread, value, flag indicating whether value is to be thrown (optional, default false).
yieldYield a value or an error from current thread. Arguments: value, flag indicating whether value is to be thrown (optional, default false).
currentGet currently running Thread object.

The Thread constructor is a function which can be called both as an ordinary function and as a constructor. The behavior is the same in both cases:

Duktape.Thread.prototype

PropertyDescription
No properties at the moment.

Duktape.Logger (constructor)

PropertyDescription
prototypePrototype for Logger objects.
clogRepresentative logger for log entries written from C code.

Called as a constructor, creates a new Logger object with a specified name (first argument). If the name is omitted, Logger will automatically assign a name based on the calling function's fileName. If called as a normal function, throws a TypeError.

Logger instances have the following properties:

To write log entries:

var logger = new Duktape.Logger();
logger.info('three values:', val1, val2, val3);

For now, see the internal documentation on logging for more info.

Tail calling might theoretically affect the automatic name assignment (i.e. when logger name argument is omitted). However, constructor calls are never converted to tail calls, so this is not a practical issue.

Duktape.Logger.prototype

PropertyDescription
rawOutput a formatted log line (buffer value), by default writes to stderr.
fmtFormat a single (object) argument.
traceWrite a trace level (level 0, TRC) log entry.
debugWrite a debug level (level 1, DBG) log entry.
infoWrite an info level (level 2, INF) log entry.
warnWrite a warn level (level 3, WRN) log entry.
errorWrite an error level (level 4, ERR) log entry.
fatalWrite a fatal level (level 5, FTL) log entry.
lDefault log level, initial value is 2 (info).
nDefault logger name, initial value is "anon".