This section describes Duktape-specific built-in objects, methods, and values.
Property | Description |
---|---|
Duktape | The Duktape built-in object. Contains miscellaneous implementation specific stuff. |
Proxy | Proxy constructor borrowed from ES6 draft (not part of Ecmascript E5/E5.1). |
Non-standard, browser-like function for writing to stdout . | |
alert | Non-standard, browser-like function for writing to stderr . |
print()
writes to stdout
with an automatic
flush afterwards. The bytes written depend on the arguments:
stdout
as is. This allows raw byte streams
to be reliably written.stdout
. For instance, print('foo', 'bar')
would write the bytes 66 6f 6f 20 62 61 72 0a
. Non-ASCII
characters are written directly in their internal extended UTF-8
representation; for most strings this means that output data is
properly UTF-8 encoded. Terminal encoding, locale, platform newline
conventions etc. have no effect on the output.alert()
behaves the same way, but writes to
stderr
. Unlike a browser alert()
, the call
does not block.
Property | Description |
---|---|
version | Duktape version number: (major * 10000) + (minor * 100) + patch . |
env | Cryptic, version dependent summary of most important effective options like endianness and architecture. |
fin | Set or get finalizer of an object. |
enc | Encode a value (hex, base-64, JX, JC): Duktape.enc('hex', 'foo') . |
dec | Decode a value (hex, base-64, JX, JC): Duktape.dec('base64', 'Zm9v') . |
info | Get internal information (such as heap address and alloc size) of a value in a version specific format. |
line | Get current line number. |
act | Get information about call stack entry. |
gc | Trigger mark-and-sweep garbage collection. |
compact | Compact the memory allocated for a value (object). |
errCreate | Callback to modify/replace a created error. |
errThrow | Callback to modify/replace an error about to be thrown. |
Buffer | Buffer constructor (function). |
Pointer | Pointer constructor (function). |
Thread | Thread constructor (function). |
Logger | Logger constructor (function). |
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
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
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()
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()
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
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:
info()
call.DUK_TYPE_xxx
from duktape.h
.Type | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
---|---|---|---|---|---|---|---|---|---|---|
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 | - | - | - | - | - | - | - | - | - |
Get the line number of the call site. This may be useful for debugging, e.g.:
log.info('reached line:', Duktape.line());
Duktape.act()
provides more information, this function
will probably be removed.
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());
Trigger a forced mark-and-sweep collection. If mark-and-sweep is disabled, this call is a no-op.
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.
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.
Property | Description |
---|---|
prototype | Prototype 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:
Duktape.Buffer.prototype
object.Duktape.Buffer(String(orig_buf))
. Buffers
are currently mostly intended to be operated with from C code.
Property | Description |
---|---|
toString | Convert Buffer to a printable string. |
valueOf | Return 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());
Property | Description |
---|---|
prototype | Prototype for Pointer objects. |
The Pointer constructor is a function which can be called both as an ordinary function and as a constructor:
ToPointer
coercion. The return value is a plain
pointer (not a Pointer object).ToPointer
coercion. Returns a Pointer object
whose internal value is the pointer resulting from the coercion. The
internal prototype of the newly created Pointer will be the
Duktape.Pointer.prototype
object.Property | Description |
---|---|
toString | Convert Pointer to a printable string. |
valueOf | Return 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());
Property | Description |
---|---|
prototype | Prototype for Thread objects. |
resume | Resume target thread with a value or an error. Arguments: target thread, value, flag indicating whether value is to be thrown (optional, default false). |
yield | Yield a value or an error from current thread. Arguments: value, flag indicating whether value is to be thrown (optional, default false). |
current | Get 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:
TypeError
is thrown). The return value is a new thread whose initial function is
recorded to be the argument function (this function will start executing
when the new thread is first resumed). The internal prototype of the
newly created Thread will be the Duktape.Thread.prototype
object.Property | Description |
---|---|
No properties at the moment. |
Property | Description |
---|---|
prototype | Prototype for Logger objects. |
clog | Representative 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:
n
: logger name; the property will be missing if (a) the given
name is not a string, or (b) no name is given and the automatic assignment
fails. The logger will then inherit a value from the Logger prototype.
You can manually set this property later to whatever value is desired.l
: log level, indicates the minimum log level to output.
This property is not assigned by default and the logger inherits a default
level from the Logger prototype. You can manually set this property to
another value to control log level on a per-logger basis.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.
Property | Description |
---|---|
raw | Output a formatted log line (buffer value), by default writes to stderr . |
fmt | Format a single (object) argument. |
trace | Write a trace level (level 0, TRC) log entry. |
debug | Write a debug level (level 1, DBG) log entry. |
info | Write an info level (level 2, INF) log entry. |
warn | Write a warn level (level 3, WRN) log entry. |
error | Write an error level (level 4, ERR) log entry. |
fatal | Write a fatal level (level 5, FTL) log entry. |
l | Default log level, initial value is 2 (info). |
n | Default logger name, initial value is "anon". |