Fork me on GitHub
Duktape API

介绍 §

版本号: 2.0.0 (2017-01-02)

文档介绍范围 §

Duktape API (在 duktape.h中定义) 是一组常量和API调用,它们允许C/C++程序与Ecmascript代码进行交互,并隐藏其中的细节如值的表示方式。

本文档提供了Duktape API及其核心概念的简明参考。如果你是Duktape的新手,请先阅读 Duktape编程指南

使用浏览器搜索函数 §

您可以使用浏览器搜索功能(通常为CTRL-F)并通过在搜索项前添加一个点来搜索函数定义。例如,使用“.duk_example_func”来查找 duk_example_func()。在大多数浏览器中,只能找到定义函数的实际部分。

API 安全性 §

一般情况下,API函数调用会检查其所有参数,并容许NULL参数和无效的值堆栈索引,使其不会有不安全的行为(崩溃)。

一个主要的例外是Duktape上下文参数ctx。除非另有说明,否则不进行检查,它必须为非NULL否则将有可能发生不安全的行为。 这是因为对其参数的显式检查将增加代码空间占用,而实际增益很小。

另请参阅 错误处理 最佳实践,特别是避免那些难以诊断且致命的未捕获错误。

API函数调用可能是宏 §

所有Duktape API函数调用都是潜在的宏。 即使在兼容的版本之间,一个API函数的实现也可以在宏和实际函数之间变换。 有关更多讨论,请参阅 Duktape API

最简单的Duktape程序 §

#include "duktape.h"

int main(int argc, char *argv[]) {
    duk_context *ctx = duk_create_heap_default();
    if (ctx) {
        duk_eval_string(ctx, "print('Hello world from Javascript!');");
        duk_destroy_heap(ctx);
    }
    return 0;
}

符号标记法 §

值堆栈 §

本文档使用以下堆栈符号标记。栈用向右延伸的可视化标记表示。例如,执行以下代码之后:

duk_push_number(ctx, 123);
duk_push_string(ctx, "foo");
duk_push_true(ctx);

堆栈看起来是这样:

[ 123 "foo" true ]

堆栈上不影响操作的元素由单个省略号("...")表示:

[ . . . ]

参与操作的元素,无论是读取,写入,插入还是删除,都具有白色背景色:

[ . . . obj key ]

在API函数调用中由显式索引标识的元素周围都有省略号元素,以强调它们可以在堆栈中任何位置:

[ . . . obj . . . key value ]

在某些情况下,元素的索引位置可以用括号中的数字或符号值来强调:

[ . . . val(index) val(index+1) . . . ]

堆栈变化用一个箭头及两个堆栈表示:

[ . . . obj . . . key value ] [ . . . obj . . . ]

相关概念 §

堆(Heap) §

用于垃圾回收的单个区域。由一个或多个上下文共享。

上下文(Context) §

在Duktape API中使用的句柄,与Duktape线程(协程)及其调用,以及值堆栈相关联。

堆栈调用(在上下文中)(Call stack (of a context)) §

上下文活动函数调用链记录。包括Ecmascript和Duktape/C函数调用。

值堆栈(上下文中)(Value stack (of a context)) §

存储上下文堆栈调用中已标记的值。

值堆栈中保存的值是传统的标记 类型 。堆栈索引可从底部 (>= 0) 或顶部 (< 0) 计算,以供最近的函数调用。

值堆栈索引(Value stack index) §

非负索引 (>= 0) 相对于栈底(译者注:栈底为0)

[ 0 1 2 3 4 5 ]

负索引 (< 0) 相对于栈顶(译者注:栈顶为-1)

[ -6 -5 -4 -3 -2 -1 ]

特殊常量 DUK_INVALID_INDEX 是一个负整数,表示无效的堆栈索引。 它可以从API函数调用中返回,也可以提供给API函数调用以指示“无值”。

值堆栈顶部 (或只是“顶部”)是刚好高于当前最高已使用索引的一个非负索引。 例如,当前最高已使用的索引是5,那么栈顶就是6。栈顶索引指示着当前栈的大小,并且也是推送到栈的下一个元素的索引。

[ 0 1 2 3 4 5 6 ]

API堆栈操作总是局限于当前堆栈帧。其它函数没有途径引用当前操作下的堆栈条目。这是故意设计成这样的,因为它保护着调用堆栈的函数不会影响其它函数调用的值。

堆栈类型 §

类型类型常量类型掩码常量描述堆分配
(none)DUK_TYPE_NONEDUK_TYPE_MASK_NONE无类型(缺失值,无效索引等)no
undefinedDUK_TYPE_UNDEFINEDDUK_TYPE_MASK_UNDEFINED未定义undefinedno
nullDUK_TYPE_NULLDUK_TYPE_MASK_NULLnullno
booleanDUK_TYPE_BOOLEANDUK_TYPE_MASK_BOOLEANtruefalseno
numberDUK_TYPE_NUMBERDUK_TYPE_MASK_NUMBERIEEE doubleno
stringDUK_TYPE_STRINGDUK_TYPE_MASK_STRING不可变字符串yes
objectDUK_TYPE_OBJECTDUK_TYPE_MASK_OBJECT带属性的对象yes
bufferDUK_TYPE_BUFFERDUK_TYPE_MASK_BUFFER可变字节缓冲区,固定/动态yes
pointerDUK_TYPE_POINTERDUK_TYPE_MASK_POINTER不透明指针(void *)no
lightfuncDUK_TYPE_LIGHTFUNCDUK_TYPE_MASK_LIGHTFUNC清楚的 Duktape/C指针(非对象)no

“堆分配”列指示该值是否指向其他的堆分配对象(如对象属性表)。

堆栈类型掩码 §

每个堆栈类型具有一个位索引,它允许堆栈类型被表示为位掩码。此掩码可用于检查某个堆栈值是否属于某些类型。 例如:

if (duk_get_type_mask(ctx, -3) & (DUK_TYPE_MASK_NUMBER |
                                  DUK_TYPE_MASK_STRING |
                                  DUK_TYPE_MASK_OBJECT)) {
    printf("type is number, string, or object\n");
}

下面的API调用可以更方便地检查是否属于某些类型:

if (duk_check_type_mask(ctx, -3, DUK_TYPE_MASK_NUMBER |
                                 DUK_TYPE_MASK_STRING |
                                 DUK_TYPE_MASK_OBJECT)) {
    printf("type is number, string, or object\n");
}

数组索引 §

Ecmascript对象和数组的键(key)只能是字符串; 这表示数组索引(0,1,2,...)实际上表示("0","1","2",...),整数索引的范围为[0, 2**32-1]。 也就是说,在属性查找中使用的任何键都被强制转换为字符串,因此 obj[123] 实际上只是 obj["123"] 的简写。

Duktape尽量避免数组访问时由数字显式转换成字符串,因此使用Duktape API时最好在Ecmascript代码和C代码中都使用数字索引。

Duktape/C 函数 §

具有Duktape/C API签名的C函数可以与Ecmascript函数对象或lightfunc值相关联,并且从Ecmascript代码调用其关联值时被调用。例如:

int my_func(duk_context *ctx) {
    duk_push_int(ctx, 123);
    return 1;
}

当相应的Ecmascript函数对象创建时,堆栈中的参数个数就已确定:固定数量的参数 DUK_VARARGS 要“按原样”获取。多余的参数会被丢弃,缺少的参数则根据需要用 undefined 填充。可使用 duk_get_top() 来确定实际参数的数量。

函数返回值:

当使用错误标示时,将没有其它错误信息:

int my_func(duk_context *ctx) {
    if (duk_get_top(ctx) == 0) {
        /* throw TypeError if no arguments given */
        return DUK_RET_TYPE_ERROR;
    }
    /* ... */
}

储藏(Stashes) §

储藏是在C代码中可通过Duktape/C API访问但却无法在Ecmascript代码中访问的对象。储藏允许C代码存储其内部状态,它可以安全地与Ecmascript代码隔离。有以下三种储藏对象:


标头定义 §

本节总结了 duktape.h. 中一些常用的标头定义。这当然不是详尽的,为方便阅读已重新组织摘录; 如有疑问,请直接查找标头。

Duktape 版本号 §

Duktape版本号定义于 DUK_VERSION 常量,使用数值 (大版本号 * 10000 + 小版本号 * 100 + 补丁) 表示。在Ecmascript代码中可使用 Duktape.version 访问该值。例如,版本号1.2.3 是将 DUK_VERSIONDuktape.version 设置为 10203,对于预发布版本 DUK_VERSION 会比实际发布版本号少1,例如,1199 用于 0.12.0 预发布版本,10299 用于 1.3.0 预发布版本。 具体请参阅 版本控制

Git 信息 §

以下Git标识符可用(全部参考 Duktape GitHub仓库 ):

DUK_GIT_DESCRIBE Git描述字符串用于Duktape构建中。对于官方发布版本,只有“v1.0.0”或类似的字符串,但对于快照构建版本它将提供有用的版本信息,例如,“V1.0.0-155-g5b7ef1f-dirty”。
DUK_GIT_COMMIT 萃取自构建时所提交的hash。
DUK_GIT_BRANCH 构建发布分支。这对于开发分支的识别很有用。

在Ecmascript环境中没有等效的定义。

调试协议版本 §

调试协议的版本号(一个整数)定义于 DUK_DEBUG_PROTOCOL_VERSION

结构体和typedef §

typedef struct duk_hthread duk_context;

typedef duk_ret_t (*duk_c_function)(duk_context *ctx);
typedef void *(*duk_alloc_function) (void *udata, duk_size_t size);
typedef void *(*duk_realloc_function) (void *udata, void *ptr, duk_size_t size);
typedef void (*duk_free_function) (void *udata, void *ptr);
typedef void (*duk_fatal_function) (duk_context *ctx, duk_errcode_t code, const char *msg);
typedef void (*duk_decode_char_function) (void *udata, duk_codepoint_t codepoint);
typedef duk_codepoint_t (*duk_map_char_function) (void *udata, duk_codepoint_t codepoint);
typedef duk_ret_t (*duk_safe_call_function) (duk_context *ctx);
typedef duk_size_t (*duk_debug_read_function) (void *udata, char *buffer, duk_size_t length);
typedef duk_size_t (*duk_debug_write_function) (void *udata, const char *buffer, duk_size_t length);
typedef duk_size_t (*duk_debug_peek_function) (void *udata);
typedef void (*duk_debug_read_flush_function) (void *udata);
typedef void (*duk_debug_write_flush_function) (void *udata);
typedef void (*duk_debug_detached_function) (void *udata);

struct duk_memory_functions {
        duk_alloc_function alloc_func;
        duk_realloc_function realloc_func;
        duk_free_function free_func;
        void *udata;
};
typedef struct duk_memory_functions duk_memory_functions;

struct duk_function_list_entry {
	const char *key;
	duk_c_function value;
	duk_int_t nargs;
};
typedef struct duk_function_list_entry duk_function_list_entry;

struct duk_number_list_entry {
	const char *key;
	duk_double_t value;
};
typedef struct duk_number_list_entry duk_number_list_entry;

错误码 §

#define DUK_ERR_NONE                 0    /* no error (e.g. from duk_get_error_code()) */
#define DUK_ERR_ERROR                100  /* Error */
#define DUK_ERR_EVAL_ERROR           101  /* EvalError */
#define DUK_ERR_RANGE_ERROR          102  /* RangeError */
#define DUK_ERR_REFERENCE_ERROR      103  /* ReferenceError */
#define DUK_ERR_SYNTAX_ERROR         104  /* SyntaxError */
#define DUK_ERR_TYPE_ERROR           105  /* TypeError */
#define DUK_ERR_URI_ERROR            106  /* URIError */

Duktape/C 函数返回码 §

/* Return codes for C functions */
#define DUK_RET_ERROR                (-DUK_ERR_ERROR)
#define DUK_RET_EVAL_ERROR           (-DUK_ERR_EVAL_ERROR)
#define DUK_RET_RANGE_ERROR          (-DUK_ERR_RANGE_ERROR)
#define DUK_RET_REFERENCE_ERROR      (-DUK_ERR_REFERENCE_ERROR)
#define DUK_RET_SYNTAX_ERROR         (-DUK_ERR_SYNTAX_ERROR)
#define DUK_RET_TYPE_ERROR           (-DUK_ERR_TYPE_ERROR)
#define DUK_RET_URI_ERROR            (-DUK_ERR_URI_ERROR)

/* Return codes for protected calls (duk_safe_call(), duk_pcall()). */
#define DUK_EXEC_SUCCESS             0
#define DUK_EXEC_ERROR               1

duk_compile() 编译选项 §

/* Compilation flags for duk_compile() and duk_eval() */
#define DUK_COMPILE_EVAL                  (1 << 0)    /* compile eval code (instead of program) */
#define DUK_COMPILE_FUNCTION              (1 << 1)    /* compile function code (instead of program) */
#define DUK_COMPILE_STRICT                (1 << 2)    /* use strict (outer) context for program, eval, or function */

duk_def_prop() 选项 §

/* Flags for duk_def_prop() and its variants */
#define DUK_DEFPROP_WRITABLE              (1 << 0)    /* set writable (effective if DUK_DEFPROP_HAVE_WRITABLE set) */
#define DUK_DEFPROP_ENUMERABLE            (1 << 1)    /* set enumerable (effective if DUK_DEFPROP_HAVE_ENUMERABLE set) */
#define DUK_DEFPROP_CONFIGURABLE          (1 << 2)    /* set configurable (effective if DUK_DEFPROP_HAVE_CONFIGURABLE set) */
#define DUK_DEFPROP_HAVE_WRITABLE         (1 << 3)    /* set/clear writable */
#define DUK_DEFPROP_HAVE_ENUMERABLE       (1 << 4)    /* set/clear enumerable */
#define DUK_DEFPROP_HAVE_CONFIGURABLE     (1 << 5)    /* set/clear configurable */
#define DUK_DEFPROP_HAVE_VALUE            (1 << 6)    /* set value (given on value stack) */
#define DUK_DEFPROP_HAVE_GETTER           (1 << 7)    /* set getter (given on value stack) */
#define DUK_DEFPROP_HAVE_SETTER           (1 << 8)    /* set setter (given on value stack) */
#define DUK_DEFPROP_FORCE                 (1 << 9)    /* force change if possible, may still fail for e.g. virtual properties */
#define DUK_DEFPROP_SET_WRITABLE          (DUK_DEFPROP_HAVE_WRITABLE | DUK_DEFPROP_WRITABLE)
#define DUK_DEFPROP_CLEAR_WRITABLE        DUK_DEFPROP_HAVE_WRITABLE
#define DUK_DEFPROP_SET_ENUMERABLE        (DUK_DEFPROP_HAVE_ENUMERABLE | DUK_DEFPROP_ENUMERABLE)
#define DUK_DEFPROP_CLEAR_ENUMERABLE      DUK_DEFPROP_HAVE_ENUMERABLE
#define DUK_DEFPROP_SET_CONFIGURABLE      (DUK_DEFPROP_HAVE_CONFIGURABLE | DUK_DEFPROP_CONFIGURABLE)
#define DUK_DEFPROP_CLEAR_CONFIGURABLE    DUK_DEFPROP_HAVE_CONFIGURABLE

duk_enum() 枚举选项 §

/* Enumeration flags for duk_enum() */
#define DUK_ENUM_INCLUDE_NONENUMERABLE    (1 << 0)    /* enumerate non-numerable properties in addition to enumerable */
#define DUK_ENUM_INCLUDE_INTERNAL         (1 << 1)    /* enumerate internal properties */
#define DUK_ENUM_OWN_PROPERTIES_ONLY      (1 << 2)    /* don't walk prototype chain, only check own properties */
#define DUK_ENUM_ARRAY_INDICES_ONLY       (1 << 3)    /* only enumerate array indices */
#define DUK_ENUM_SORT_ARRAY_INDICES       (1 << 4)    /* sort array indices (applied to full enumeration result, including inherited array indices) */
#define DUK_ENUM_NO_PROXY_BEHAVIOR        (1 << 5)    /* enumerate a proxy object itself without invoking proxy behavior */

duk_gc()垃圾回收选项 §

/* Flags for duk_gc() */
#define DUK_GC_COMPACT                    (1 << 0)    /* compact heap objects */

强制提示 §

/* Coercion hints */
#define DUK_HINT_NONE         0    /* prefer number, unless coercion input is a Date, in which case prefer string (E5 Section 8.12.8) */
#define DUK_HINT_STRING       1    /* prefer string */
#define DUK_HINT_NUMBER       2    /* prefer number */

duk_push_thread_raw() 选项 §

/* Flags for duk_push_thread_raw() */
#define DUK_THREAD_NEW_GLOBAL_ENV         (1 << 0)    /* create a new global environment */

其他定义 §

#define DUK_INVALID_INDEX     DUK_IDX_MIN

#define DUK_VARARGS           ((duk_int_t) (-1))

#define DUK_API_ENTRY_STACK   64

API 函数列表 §

1.0.0 §

1.1.0 §

1.2.0 §

1.3.0 §

1.4.0 §

1.5.0 §

1.6.0 §

2.0.0 §

borrowed §

buffer §

bufferobject §

bytecode §

call §

codec §

compare §

compile §

debug §

debugger §

error §

experimental §

finalizer §

function §

heap §

inspect §

json §

lightfunc §

magic §

memory §

module §

object §

property §

protected §

prototype §

sandbox §

slice §

stack §

stash §

string §

symbol §

thread §

time §

vararg §


.duk_alloc() 1.0.0 memory §

原型 §

void *duk_alloc(duk_context *ctx, duk_size_t size);

堆栈 §

(对值堆栈没有影响。)

摘要 §

类似于 duk_alloc_raw() ,但它可能触发垃圾回收以满足请求。此操作所分配的内存本身不会自动进行垃圾回收。即使在垃圾回收后,分配内存请求也有可能失败,在这种情况下将返回 NULL 。分配的内存不会自动清理,并且可能包含无用信息。

可以使用 duk_free()duk_free_raw() 释放 duk_alloc() 所分配的内存。

示例 §

/* 虽然 duk_alloc() 在必要时会触发GC,但它仍然有可能无法分配所需的内存。
 * 调用者必须检查返回值 NULL 。
 * (如果分配的内存大小为0,即使成功也有可能返回 NULL )。
 */
void *buf = duk_alloc(ctx, 1024);
if (buf) {
    printf("allocation successful: %p\n", buf);
} else {
    printf("allocation failed\n");
}

请参阅 §


.duk_alloc_raw() 1.0.0 memory §

原型 §

void *duk_alloc_raw(duk_context *ctx, duk_size_t size);

堆栈 §

(对值堆栈没有影响。)

摘要 §

由已注册到上下文的原始分配函数 分配字节数 。如果分配失败,则返回 NULL 。如果 分配字节数 为零,则该调用可能返回 NULL 或一些可被其它函数安全释放的非 NULL 值,这些函数如 duk_free_raw() 。此分配内存不能触发垃圾回收,并且分配的内存不会自动进行垃圾回收。分配的内存不会自动清理,并且可能包含无用信息。

可以使用 duk_free()duk_free_raw() 释放 duk_alloc_raw() 所分配的内存。

示例 §

void *buf = duk_alloc_raw(ctx, 1024);
if (buf) {
    printf("allocation successful: %p\n", buf);
} else {
    printf("allocation failed\n");
}

请参阅 §


.duk_base64_decode() 1.0.0 codec §

原型 §

void duk_base64_decode(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . base64_val . . . ] [ . . . val . . . ]

摘要 §

将base-64编码的值解码并转入一个 buffer 。如果输入无效,则抛出错误。

示例 §

duk_push_string(ctx, "Zm9v");
duk_base64_decode(ctx, -1);  /* buffer */
printf("base-64 decoded: %s\n", duk_to_string(ctx, -1));
duk_pop(ctx);

/* Output:
 * base-64 decoded: foo
 */

请参阅 §


.duk_base64_encode() 1.0.0 codec §

原型 §

const char *duk_base64_encode(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ] [ . . . base64_val . . . ]

摘要 §

将任意值强制转换成一个 buffer,然后直接对其进行 base-64 编码。为方便已见,将返回一个指向结果字符串的指针。

强制转换成 buffer 之前得先把 non-buffer 值强制转换成字符串,然后把字符串强制转换成 buffer 。 此 buffer 包含 CESU-8 编码的字符串。

示例 §

duk_push_string(ctx, "foo");
printf("base-64 encoded: %s\n", duk_base64_encode(ctx, -1));

/* Output:
 * base-64 encoded: Zm9v
 */

请参阅 §


.duk_buffer_to_string() 2.0.0 string stack buffer §

原型 §

const char *duk_buffer_to_string(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ] [ . . . buffer_to_string(val) . . . ]

摘要 §

idx 处的 buffer 值(空 buffer 或任意 buffer 对象)转换成一个字符串,该字符串的内部字节表示形式与 buffer 比率为1:1(与使用 duk_push_lstring() 推送数据一样)。它返回一个非 NULL 指针,该指针指向一个只读且以NUL结尾的字符串数据。以下情况将抛出TypeError错误: (1) 参数不是 buffer 值,(2) 参数是 buffer 对象,但其后置 buffer 与前置 buffer 大小不一致,(3) 索引无效。

自定义类型强制转换在 类型转换与测试 中有介绍。

从 Duktape 2.0 版本开始, duk_to_string() 强制转换 buffer 值通常为"[object Uint8Array]",这通常不是故意的。

示例 §

unsigned char *ptr;
ptr = (unsigned char *) duk_push_fixed_buffer(ctx, 4);
ptr[0] = 0x61;
ptr[1] = 0x62;
ptr[2] = 0x63;
ptr[3] = 0x64;  /* 61 62 63 64 */
printf("coerced string: %s\n", duk_buffer_to_string(ctx, -1));
duk_pop(ctx);

.duk_call() 1.0.0 call §

原型 §

void duk_call(duk_context *ctx, duk_idx_t nargs);

堆栈 §

[ . . . func arg1 . . . argN ] [ . . . retval ]

摘要 §

使用参数 nargs 调用目标函数 func (参数不包括函数本身)。 最后函数及其参数被替换成一个返回值。在函数调用期间抛出的错误不会自动捕获。

目标函数中的 this 将初始化为 undefined 。如果目标函数不是严格的(not strict),则在调用函数之前, this 将被全局对象替换; 具体请参阅 深入函数代码 。 如果要自定义 this ,可以改用 duk_call_method()duk_call_prop()

此API函数调用等同于:

var retval = func(arg1, ..., argN);

或:

var retval = func.call(undefined, arg1, ..., argN);

示例 §

/* 假设目标函数已经置于栈上 func_idx 位置; 
 * 目标函数将添加参数并返回结果。
 */
duk_idx_t func_idx = /* ... */;

duk_dup(ctx, func_idx);
duk_push_int(ctx, 2);
duk_push_int(ctx, 3);
duk_call(ctx, 2);  /* [ ... func 2 3 ] -> [ 5 ] */
printf("2+3=%ld\n", (long) duk_get_int(ctx, -1));
duk_pop(ctx);

.duk_call_method() 1.0.0 call §

原型 §

void duk_call_method(duk_context *ctx, duk_idx_t nargs);

堆栈 §

[ . . . func this arg . . . argN ] [ . . . retval ]

摘要 §

使用一个显式的 this 和参数 nargs 调用目标函数 func (参数不包括函数本身和 this )。 最后函数对象、 this 和参数被替换为一个返回值。 在函数调用期间抛出的错误不会自动捕获。

如果目标函数不是严格的 (not strict),this 可能会在目标函数处理期间被修改,具体请参阅 深入函数代码

此API函数调用等同于:

var retval = func.call(this_binding, arg1, ..., argN);

示例 §

/* The target function here prints:
 *
 *    this: 123
 *    2 3
 *
 * and returns 5.
 */

duk_push_string(ctx, "function(x,y) { print('this:', this); "
                     "print(x,y); return x+y; }");
duk_eval(ctx);  /* -> [ ... func ] */
duk_push_int(ctx, 123);
duk_push_int(ctx, 2);
duk_push_int(ctx, 3);
duk_call_method(ctx, 2);  /* [ ... func 123 2 3 ] -> [ 5 ] */
printf("2+3=%ld\n", (long) duk_get_int(ctx, -1));  /* prints 5 */
duk_pop(ctx);

.duk_call_prop() 1.0.0 property call §

原型 §

void duk_call_prop(duk_context *ctx, duk_idx_t obj_idx, duk_idx_t nargs);

堆栈 §

[ . . . obj . . . key arg1 . . . argN ] [ . . . obj . . . retval ]

摘要 §

使用 nargs 参数调用 obj.keythis 设置为 obj 。 最后属性名和参数被替换为一个返回值; 此操作不触及目标对象。函数调用期间的错误将不会自动捕获。

如果目标函数不是严格的 (not strict),this 可能会在目标函数处理期间被修改,具体请参阅 深入函数代码

此API函数调用等同于:

var retval = obj[key](arg1, ..., argN);

或:

var func = obj[key];
var retval = func.call(obj, arg1, ..., argN);
虽然访问其属性的基础值通常是对象,但它其实可以是任意值。纯字符串和buffer值具有虚拟索引属性,因此您可以像这样访问 "foo"[2]。 大多数原始值(primitive value)也是继承于一些原型对象(prototype object),所以你可以像这样调用它们: (12345).toString(16)

示例 §

/* obj.myAdderMethod(2,3) -> 5 */
duk_idx_t obj_idx = /* ... */;

duk_push_string(ctx, "myAdderMethod");
duk_push_int(ctx, 2);
duk_push_int(ctx, 3);
duk_call_prop(ctx, obj_idx, 2);  /* [ ... "myAdderMethod" 2 3 ] -> [ ... 5 ] */
printf("2+3=%ld\n", (long) duk_get_int(ctx, -1));
duk_pop(ctx);

.duk_char_code_at() 1.0.0 string §

原型 §

duk_codepoint_t duk_char_code_at(duk_context *ctx, duk_idx_t idx, duk_size_t char_offset);

堆栈 §

[ . . . str . . . ]

摘要 §

获取字符串中偏移量为 char_offset 的码点值(codepoint),此字符串位于栈上 idx 处。如果在栈上 idx 处的值不是字符串,则抛出错误。如果字符串不能解码为(扩展的)UTF-8,则返回结果为U+FFFD(Unicode替换字符)。如果 char_offset 无效(在字符串外部),则返回0。

示例 §

printf("char code at char index 12: %ld\n", (long) duk_char_code_at(ctx, -3, 12));

.duk_check_stack() 1.0.0 stack §

原型 §

duk_bool_t duk_check_stack(duk_context *ctx, duk_idx_t extra);

堆栈 §

(对值堆栈没有影响。)

摘要 §

确保相对于当前栈顶,值堆栈至少有 extra 个预留(或已分配)的元素供调用者使用。如果成功返回1,否则返回0。如果调用成功,可以保证调用者能把 extra 个元素推送到值堆栈中而不会发生值堆栈相关的错误(其他的错误,如内存不足(out-of-memory)仍可能发生)。调用者不能指望能够推送多于 extra 的值; 虽然有可能被允许,但这些元素是保留给 Duktape 内部使用的。

一旦进入到 Duktape/C 函数中,在任何调用之外,除了值堆栈上的调用参数,还为调用者自动分配了预留的元素( DUK_API_ENTRY_STACK )。如果需要更多的值堆栈空间,调用者必须在函数开始时(例如,如果所需要元素的个数是已知的或者可以基于参数计算)或动态地(例如在循环内)显式预留空间。请注意,尝试将值推送到当前分配的值堆栈之外会导致错误:值堆栈不会自动扩展。这简化了内部实现。

除了用户预留的元素,Duktape 会自动维持一个内部值堆栈,以确保所有API调用都有足够的值堆栈空间使用,而不需要进一步的分配。这个值堆栈以稍大的步进(step)扩展,以最小代价进行内存重分配。因此,值堆栈的内部数量会远大于调用者所需的 extra 数量。调用者不需要考虑这一点。

一般情况下,应该使用 duk_require_stack() 而不是此函数来预留更多的堆栈空间。如果值堆栈不能扩展,除了抛出一个错误,几乎没有可用的方法了。

示例 §

duk_idx_t nargs = duk_get_top(ctx);  /* number or arguments */

/* reserve space for one temporary for each input argument */
if (!duk_check_stack(ctx, nargs * 2)) {
    /* return 'undefined' if cannot allocate space */
    printf("failed to reserve enough stack space\n");
    return 0;
}

/* ... */

请参阅 §


.duk_check_stack_top() 1.0.0 stack §

原型 §

duk_bool_t duk_check_stack_top(duk_context *ctx, duk_idx_t top);

堆栈 §

(对值堆栈没有影响。)

摘要 §

类似于 duk_check_stack() ,但是这是确保供调用者使用到 栈顶 的空间。这有时比指定预留元素(相对于当前栈顶)数量更方便。

调用者指定的最大栈顶确保是给调用者使用,而不是为调用者预留的最高值堆栈索引。例如,如果 栈顶 为500,则为调用者预留的最高值堆栈索引为499。

一般情况下,应该使用 duk_require_stack_top() 而不是此函数来预留更多的堆栈空间。如果值堆栈不能扩展,除了抛出一个错误,几乎没有可用的方法了。

示例 §

if (duk_check_stack_top(ctx, 100)) {
    printf("value stack guaranteed up to index 99\n");
} else {
    printf("cannot get value stack space\n");
}

.duk_check_type() 1.0.0 stack §

原型 §

duk_bool_t duk_check_type(duk_context *ctx, duk_idx_t idx, duk_int_t type);

堆栈 §

[ . . . val . . . ]

摘要 §

将堆栈 idx 处的值类型与给定的类型比较。如果类型一样,则返回1,否则返回0。

示例 §

if (duk_check_type(ctx, -3, DUK_TYPE_NUMBER)) {
    printf("value is a number\n");
}

.duk_check_type_mask() 1.0.0 stack §

原型 §

duk_bool_t duk_check_type_mask(duk_context *ctx, duk_idx_t idx, duk_uint_t mask);

堆栈 §

[ . . . val . . . ]

摘要 §

将堆栈 idx 处的值的类型掩码与给定的 mask 比较。如果类型掩码一样,则返回1,否则返回0。

示例 §

if (duk_check_type_mask(ctx, -3, DUK_TYPE_MASK_STRING |
                                 DUK_TYPE_MASK_NUMBER)) {
    printf("value is a string or a number\n");
}

.duk_compact() 1.0.0 property object memory §

原型 §

void duk_compact(duk_context *ctx, duk_idx_t obj_idx);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Resizes an object's internal memory allocation to minimize memory usage. If the value at obj_idx is not an object, does nothing. Although compaction is normally safe, it can fail due to an internal error (such as out-of-memory error). Compaction only affects to an object's "own properties", not its inherited properties.

Compaction is not a final operation and has no impact on object semantics. Adding new properties to the object is still possible (assuming the object is extensible), but causes an object resize. Existing property values can be changed (assuming the properties are writable) without affecting the object's internal memory allocation. An object can be compacted multiple times: for instance, if a new property is added to a previously compacted object, the object can be compacted again to minimize memory footprint after the property addition.

Compacting an object saves a small amount of memory per object. It is generally useful when (1) memory footprint is very important, (2) an object is unlikely to gain new properties, (3) an object is relatively long-lived, and (4) when compaction can be applied to enough many objects to make a significant difference.

If Object.seal(), Object.freeze(), or Object.preventExtensions() is called, an object is automatically compacted.

示例 §

duk_push_object(ctx);                           /* [ ... obj ] */
duk_push_int(ctx, 42);                          /* [ ... obj 42 ] */
duk_put_prop_string(ctx, -2, "meaningOfLife");  /* [ ... obj ] */
duk_compact(ctx, -1);                           /* [ ... obj ] */

.duk_compile() 1.0.0 compile §

原型 §

void duk_compile(duk_context *ctx, duk_uint_t flags);

堆栈 §

[ . . . source filename ] [ . . . function ]

摘要 §

Compile Ecmascript source code and replace it with a compiled function object (the code is not executed). The filename argument is stored as the fileName property of the resulting function, and is the name used in e.g. tracebacks to identify the function. May throw a SyntaxError for any compile-time errors (in addition to the usual internal errors like out-of-memory, internal limit errors, etc).

The following flags may be given:

  • DUK_COMPILE_EVAL: compile the input as eval code instead of as an Ecmascript program
  • DUK_COMPILE_FUNCTION: compile the input as a function instead of as an Ecmascript program
  • DUK_COMPILE_STRICT: force the input to be compiled in strict mode

The source code being compiled may be:

  • Global code: compiles into a function with zero arguments, which executes like a top level Ecmascript program (default)
  • Eval code: compiles into a function with zero arguments, which executes like an Ecmascript eval call (flag DUK_COMPILE_EVAL)
  • Function code: compiles into a function with zero or more arguments (flag DUK_COMPILE_FUNCTION)

All of these have slightly different semantics in Ecmascript. See Establishing an Execution Context for a detailed discussion. One major difference is that global and eval contexts have an implicit return value: the last non-empty statement value is an automatic return value for the program or eval code, whereas functions don't have an automatic return value.

Global and eval code don't have an explicit function syntax. For instance, the following can be compiled both as a global and as an eval expression:

print("Hello world!");
123;  // implicit return value

Function code follows the Ecmascript function syntax (the function name is optional):

function adder(x,y) {
    return x+y;
}

Compiling a function is equivalent to compiling eval code which contains a function expression. Note that the outermost parentheses are required, otherwise the eval code will register a global function named "adder" instead of returning a plain function value:

(function adder(x,y) {
    return x+y;
})

The bytecode generated for global and eval code is currently slower than that generated for functions: a "slow path" is used for all variable accesses in program and eval code, and the implicit return value handling of program and eval code generates some unnecessary bytecode. From a performance point of view (both memory and execution performance) it is thus preferable to have as much code inside functions as possible.

When compiling eval and global expressions, be careful to avoid the usual Ecmascript gotchas, such as:

/* Function at top level is a function declaration which registers a global
 * function, and is different from a function expression.  Use parentheses
 * around the top level expression.
 */

eval("function adder(x,y) { return x+y; }");   /* registers 'adder' to global */
eval("function (x,y) { return x+y; }");        /* not allowed */
eval("(function (x,y) { return x+y; })");      /* function expression (anonymous) */
eval("(function adder(x,y) { return x+y; })"); /* function expression (named) */

/* Opening curly brace at top level is interpreted as start of a block
 * expression, not an object literal.  Use parentheses around the top
 * level expression.
 */

eval("{ myfunc: 1 }");   /* block with -label- "myfunc" and statement "1" (!) */
eval("({ myfunc: 1 })";  /* object literal { myfunc: 1 } */

示例 §

/* Global code.  Note that the hello() function is a function
 * declaration which gets registered into the global object when
 * executed.  Implicit return value is 123.
 */

duk_push_string(ctx, "print('global');\n"
                     "function hello() { print('Hello world!'); }\n"
                     "123;");
duk_push_string(ctx, "hello");
duk_compile(ctx, 0);   /* [ source filename ] -> [ func ] */
duk_call(ctx, 0);      /* [ func ] -> [ result ] */
printf("program result: %lf\n", (double) duk_get_number(ctx, -1));
duk_pop(ctx);

/* Eval code */

duk_push_string(ctx, "2+3");
duk_push_string(ctx, "eval");
duk_compile(ctx, DUK_COMPILE_EVAL);
duk_call(ctx, 0);      /* [ func ] -> [ result ] */
printf("eval result: %lf\n", (double) duk_get_number(ctx, -1));
duk_pop(ctx);

/* Function code */

duk_push_string(ctx, "function (x,y) { return x+y; }");
duk_push_string(ctx, "function");
duk_compile(ctx, DUK_COMPILE_FUNCTION);
duk_push_int(ctx, 5);
duk_push_int(ctx, 6);
duk_call(ctx, 2);      /* [ func 5 6 ] -> [ result ] */
printf("function result: %lf\n", (double) duk_get_number(ctx, -1));
duk_pop(ctx);

.duk_compile_lstring() 1.0.0 compile §

原型 §

void duk_compile_lstring(duk_context *ctx, duk_uint_t flags, const char *src, duk_size_t len);

堆栈 §

[ . . . ] [ . . . function ]

摘要 §

Like duk_compile(), but the compile input is given as a C string with explicit length. The filename associated with the function is "input".

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

const char *src = /* ... */;
duk_size_t len = /* ... */;

duk_compile_lstring(ctx, 0, src, len);

.duk_compile_lstring_filename() 1.0.0 compile §

原型 §

void duk_compile_lstring_filename(duk_context *ctx, duk_uint_t flags, const char *src, duk_size_t len);

堆栈 §

[ . . . filename ] [ . . . function ]

摘要 §

Like duk_compile(), but the compile input is given as a C string with explicit length.

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

const char *src = /* ... */;
duk_size_t len = /* ... */;

duk_push_string(ctx, "myFile.js");
duk_compile_lstring_filename(ctx, 0, src, len);

.duk_compile_string() 1.0.0 compile §

原型 §

void duk_compile_string(duk_context *ctx, duk_uint_t flags, const char *src);

堆栈 §

[ . . . ] [ . . . function ]

摘要 §

Like duk_compile(), but the compile input is given as a C string. The filename associated with the function is "input".

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

duk_compile_string(ctx, 0, "print('program code');");

.duk_compile_string_filename() 1.0.0 compile §

原型 §

void duk_compile_string_filename(duk_context *ctx, duk_uint_t flags, const char *src);

堆栈 §

[ . . . filename ] [ . . . function ]

摘要 §

Like duk_compile(), but the compile input is given as a C string.

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

duk_push_string(ctx, "myFile.js");
duk_compile_string_filename(ctx, 0, "print('program code');");

.duk_components_to_time() 2.0.0 time experimental §

原型 §

duk_double_t duk_components_to_time(duk_context *ctx, duk_time_components *comp);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Convert components (year, month, day, etc), interpreted in UTC, into a time value. The comp->weekday argument is ignored in the conversion. If the component values are invalid, an error is thrown.

There are some differences to the Ecmascript Date.UTC() built-in:

  • There's no special handling of two-digit years. For example, Date.UTC(99, 0, 1) gets interpreted as 1999-01-01. If comp->time is 99, it's interpreted as the year 99.
  • The milliseconds component is allowed fractions (sub-millisecond resolution) so that the resulting time value may have fractions.

Like the Ecmascript primitives, the components can exceed their natural range and are normalized. For example, specifying comp->minutes as 120 is interpreted as adding 2 hours to the time value. The components are expressed as IEEE doubles to allow large and negative values to be used.

示例 §

duk_time_components comp;
duk_double_t time;

memset((void *) &comp, 0, sizeof(comp));  /* good practice even if fully initialized */
comp.year = 2016;
comp.month = 0;  /* 0-based, 1=January */
comp.day = 2;    /* 1-based: second of January */
comp.hours = 3;
comp.minutes = 4;
comp.seconds = 5;
comp.milliseconds = 6.0;  /* allows sub-millisecond resolution */
comp.weekday = 0;  /* ignored */

time = duk_components_to_time(ctx, &comp);
printf("2016-01-02 03:04:05.006Z -> %lf\n", (double) time);

.duk_concat() 1.0.0 string §

原型 §

void duk_concat(duk_context *ctx, duk_idx_t count);

堆栈 §

[ . . . val1 . . . valN ] [ . . . result ]

摘要 §

Concatenate zero or more values into a result string. The input values are automatically coerced with ToString().

This primitive minimizes the number of intermediate string interning operations and is better than concatenating strings manually.

示例 §

duk_push_string(ctx, "foo");
duk_push_int(ctx, 123);
duk_push_true(ctx);
duk_concat(ctx, 3);

printf("result: %s\n", duk_get_string(ctx, -1));  /* "foo123true" */
duk_pop(ctx);

请参阅 §


.duk_config_buffer() 1.3.0 stack buffer §

原型 §

void duk_config_buffer(duk_context *ctx, duk_idx_t idx, void *ptr, duk_size_t len);

堆栈 §

[ . . . buf . . . ] [ . . . buf . . . ]

摘要 §

Set the external buffer pointer and length of an external buffer value.

示例 §

/* Create an external buffer and point it to my_buffer containing
 * my_length bytes.
 */
duk_push_external_buffer(ctx);
duk_config_buffer(ctx, -1, my_buffer, my_length);

.duk_copy() 1.0.0 stack §

原型 §

void duk_copy(duk_context *ctx, duk_idx_t from_idx, duk_idx_t to_idx);

堆栈 §

[ . . . old(to_idx) . . . val(from_idx) . . . ] [ . . . val(to_idx) . . . val(from_idx) . . . ]

摘要 §

Copy a value from from_idx to to_idx, overwriting the previous value. If either index is invalid, throws an error.

This is a shorthand for:

/* to_index must be normalize in case it is negative and would change its
 * meaning after duk_dup().
 */
to_idx = duk_normalize_idx(ctx, to_idx);
duk_dup(ctx, from_idx);
duk_replace(ctx, to_idx);

示例 §

duk_copy(ctx, -3, 1);

.duk_create_heap() 1.0.0 heap §

原型 §

duk_context *duk_create_heap(duk_alloc_function alloc_func,
                             duk_realloc_function realloc_func,
                             duk_free_function free_func,
                             void *heap_udata,
                             duk_fatal_function fatal_handler);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Create a new Duktape heap and return an initial context (thread). If heap initialization fails, a NULL is returned. There is currently no way to obtain more detailed error information.

The caller may provide custom memory management functions in alloc_func, realloc_func, and free_func; the pointers must either all be NULL or all be non-NULL. If the pointers are NULL, default memory management functions (ANSI C malloc(), realloc() , and free()) are used. The memory management functions share the same opaque userdata pointer, heap_udata. This userdata pointer is also used for other Duktape features like fatal error handling and low memory pointer compression macros.

A fatal error handler is provided in fatal_handler. This handler is called in unrecoverable error situations such as uncaught errors, out-of-memory errors not resolved by garbage collection, self test errors, etc. A caller SHOULD implement a fatal error handler in most applications. If not given, a default fatal error handler built into Duktape is used instead. The default fatal error handler (unless overridden by duk_config.h) calls abort() with no error message printed to stdout or stderr. See How to handle fatal errors for more detail and examples.

To create a Duktape heap with default settings, use duk_create_heap_default().

New contexts linked to the same heap can be created with duk_push_thread() and duk_push_thread_new_globalenv().

示例 §

/*
 *  Simple case: use default allocation functions and fatal error handler
 */

duk_context *ctx = duk_create_heap(NULL, NULL, NULL, NULL, NULL);
if (ctx) {
    /* success */
} else {
    /* error */
}

/*
 *  Customized handlers
 */

duk_context *ctx = duk_create_heap(my_alloc, my_realloc, my_free,
                                   (void *) 0xdeadbeef, my_fatal);
if (ctx) {
    /* success */

    /* ... after heap is no longer needed: */
    duk_destroy_heap(ctx);
} else {
    /* error */
}

.duk_create_heap_default() 1.0.0 heap §

原型 §

duk_context *duk_create_heap_default(void);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Create a new Duktape heap and return an initial context (thread). If heap initialization fails, a NULL is returned. There is currently no way to obtain more detailed error information.

The created heap will use default memory management and fatal error handler functions. This API call is equivalent to:

ctx = duk_create_heap(NULL, NULL, NULL, NULL, NULL);

示例 §

duk_context *ctx = duk_create_heap_default();
if (ctx) {
    /* success */

    /* ... after heap is no longer needed: */
    duk_destroy_heap(ctx);
} else {
    /* error */
}

.duk_debugger_attach() 1.2.0 debugger §

原型 §

void duk_debugger_attach(duk_context *ctx,
                         duk_debug_read_function read_cb,
                         duk_debug_write_function write_cb,
                         duk_debug_peek_function peek_cb,
                         duk_debug_read_flush_function read_flush_cb,
                         duk_debug_write_flush_function write_flush_cb,
                         duk_debug_request_function request_cb,
                         duk_debug_detached_function detached_cb,
                         void *udata);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Attach a debugger to the Duktape heap. The debugger will automatically enter paused state when the attach is complete. If debugger support is not compiled into Duktape, throws an error. See debugger.rst for more information on debugger integration. The callbacks are as follows, optional callbacks may be NULL:

CallbackRequiredDescription
read_cbYesDebug transport read callback
write_cbYesDebug transport write callback
peek_cbNoDebug transport peek callback, strongly recommended but optional
read_flush_cbNoDebug transport read flush callback
write_flush_cbNoDebug transport write flush callback
request_cbNoApplication specific command (AppRequest) callback, NULL indicates no AppRequest support
detached_cbNoDebugger detached callback

Important: The callbacks are not allowed to call any Duktape API functions (doing so may cause memory unsafe behavior) except for the following:

  • The request_cb AppRequest callback may use the value stack within the guidelines described in debugger.rst.
  • Since Duktape 1.4.0 the debugger detached callback is allowed to call duk_debugger_attach() to immediately reattach the debugger. In Duktape 1.3.0 and before the immediate reattach potentially caused some issues.
The duk_debugger_attach_custom() and duk_debugger_attach() API calls were merged in Duktape 2.x.

示例 §

duk_debugger_attach(ctx,
                    my_read_cb,
                    my_write_cb,
                    my_peek_cb,
                    NULL,
                    NULL,
                    NULL,
                    my_detached_cb,
                    my_udata);

.duk_debugger_cooperate() 1.2.0 debugger §

原型 §

void duk_debugger_cooperate(duk_context *ctx);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Check for and execute inbound debug commands without blocking. Debug commands are executed in the context of the ctx argument. May only be called when no calls into Duktape are in progress (from any context). See debugger.rst for more information.

示例 §

duk_debugger_cooperate(ctx);

.duk_debugger_detach() 1.2.0 debugger §

原型 §

void duk_debugger_detach(duk_context *ctx);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Detach a debugger from the Duktape heap. If debugger support is not compiled into Duktape, throws an error. See debugger.rst for more information.

示例 §

duk_debugger_detach(ctx);

.duk_debugger_notify() 1.5.0 debugger §

原型 §

duk_bool_t duk_debugger_notify(duk_context *ctx, duk_idx_t nvalues);

堆栈 §

[ . . . val1 . . . valN ] [ . . . ]

摘要 §

Send an application specific debugger notify (AppNotify) containing the nvalues values on the value stack top mapped to debug protocol dvalues. The return value indicates whether the notify was successfully sent (non-zero) or not (zero). The nvalues arguments are always popped off the stack top. The call is a no-op if debugger support has not been compiled in, or if the debugger is not attached; in both cases the call will return zero to indicate that the notify was not sent.

See the debugger documentation for more information and examples on how to use application specific notifications.

示例 §

/* Causes the following notify to be sent over the debugger protocol:
 *
 *   NFY AppNotify "BatteryStatus" 740 1000 true EOM
 */
int battery_current = 740;
int battery_limit = 1000;
int battery_charging = 1;

duk_push_string(ctx, "BatteryStatus");
duk_push_int(ctx, battery_current);
duk_push_int(ctx, battery_limit);
duk_push_boolean(ctx, battery_charging);
if (duk_debugger_notify(ctx, 4 /*nvalues*/)) {
    printf("battery status notification sent\n");
} else {
    printf("battery status notification not sent\n");
}

.duk_debugger_pause() 1.5.0 debugger §

原型 §

void duk_debugger_pause(duk_context *ctx);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Request a debugger pause as soon as possible and return without blocking. The pause will be triggered the next time Ecmascript bytecode is executed, which is usually almost immediate. However, if a native call such as a Duktape/C function is in progress or no Ecmascript code is currently executing, it may take longer for the pause to take effect.

The call is a no-op if (1) debugger support has not been compiled in, (2) the debugger is not attached, or (3) Duktape is already paused. This mimics the semantics of the Ecmascript debugger statement.

Like all Duktape API calls, this call is not thread safe. It may be tempting to trigger a pause from a thread different than one running Ecmascript code for the context, but this is unsafe and not currently supported.

示例 §

/* In your event loop: */
if (key_pressed == KEY_F12) {
    duk_debugger_pause(ctx);
}

.duk_decode_string() 1.0.0 string §

原型 §

void duk_decode_string(duk_context *ctx, duk_idx_t idx, duk_decode_char_function callback, void *udata);

堆栈 §

[ . . . val . . . ]

摘要 §

Process string at idx, calling callback for each codepoint of the string. The callback is given the udata argument and a codepoint. The input string is not modified. If the value is not a string or the index is invalid, throws an error.

示例 §

static void decode_char(void *udata, duk_codepoint_t codepoint) {
    printf("codepoint: %ld\n", (long) codepoint);
}

duk_push_string(ctx, "test_string");
duk_decode_string(ctx, -1, decode_char, NULL);

请参阅 §


.duk_def_prop() 1.1.0 sandbox property §

原型 §

void duk_def_prop(duk_context *ctx, duk_idx_t obj_idx, duk_uint_t flags);

堆栈 §

[ . . . obj . . . key ] [ . . . obj . . . ] (if have no value, setter, getter)
[ . . . obj . . . key value ] [ . . . obj . . . ] (if have value)
[ . . . obj . . . key getter ] [ . . . obj . . . ] (if have getter, but no setter)
[ . . . obj . . . key setter ] [ . . . obj . . . ] (if have setter, but no getter)
[ . . . obj . . . key getter setter ] [ . . . obj . . . ] (if have both getter and setter)

摘要 §

Create or alter the attributes of property key of object at obj_idx, with semantics like Object.defineProperty(). When the requested change is not allowed (e.g. property is not configurable), a TypeError is thrown. If the target is not an object (or the index is invalid) an error is thrown.

If the target is a Proxy object which implements the defineProperty trap, the trap should be invoked. However, Duktape doesn't currently support the defineProperty trap. When support is added, this API call will start invoking the trap.

The flags field provides "have" flags to indicate what property attributes are changed (this models the partial property descriptors allowed by Object.defineProperty()). Values for the writable, configurable, and enumerable attributes are given in the flags field, while property value, getter, and setter are given as value stack arguments. When creating a new property, missing attribute values cause Ecmascript defaults to be used (false for all boolean attributes, undefined for value, getter, setter); when modifying an existing property missing attribute values mean that existing attribute values are not touched.

With the DUK_DEFPROP_FORCE flag property changes can be forced even when an operation would normally fail due to a non-extensible target object or a non-configurable property. This cannot be done from Ecmascript code with Object.defineProperty() and is useful for e.g. sandboxing setup. In some cases even a forced change is not possible and will cause an error to be thrown. For instance, properties implemented internally as virtual properties may not be modifiable (such as string .length and index properties) or may have limitations (such as array .length property which cannot be made configurable or enumerable due to internal limitations).

Some examples (see further examples below):

  • To set the writable attribute, set flags to DUK_DEFPROP_HAVE_WRITABLE | DUK_DEFPROP_WRITABLE.
  • To clear the writable attribute, set flags to DUK_DEFPROP_HAVE_WRITABLE.
  • To set value, clear writable, and set enumerable, set flags to DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_HAVE_WRITABLE | DUK_DEFPROP_HAVE_ENUMERABLE | DUK_DEFPROP_ENUMERABLE and provide the property value as a stack argument.
  • To forcibly set the value of a non-configurable property, set flags to DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_FORCE and provide the new property value as a stack argument.

In Duktape 1.4.0 convenience flags for setting/clearing attributes were added:

  • DUK_DEFPROP_SET_WRITABLE / DUK_DEFPROP_CLEAR_WRITABLE
  • DUK_DEFPROP_SET_ENUMERABLE / DUK_DEFPROP_CLEAR_ENUMERABLE
  • DUK_DEFPROP_SET_CONFIGURABLE / DUK_DEFPROP_CLEAR_CONFIGURABLE

This API call is useful for various things:

  • To create properties with non-default attributes directly from C code.
  • To create accessor (getter/setter) properties directly from C code.
  • To modify the property attributes of existing properties directly from C code.

See API testcase test-def-prop.c for more examples.

示例 §

duk_idx_t obj_idx = /* ... */;

/* Create an ordinary property which is writable and configurable, but
 * not enumerable.
 */

duk_push_string(ctx, "my_prop_1");
duk_push_int(ctx, 123);  /* prop value */
duk_def_prop(ctx,
             obj_idx,
             DUK_DEFPROP_HAVE_VALUE |
             DUK_DEFPROP_HAVE_WRITABLE | DUK_DEFPROP_WRITABLE |
             DUK_DEFPROP_HAVE_ENUMERABLE | 0 |
             DUK_DEFPROP_HAVE_CONFIGURABLE | DUK_DEFPROP_CONFIGURABLE);

/* In Duktape 1.4.0 there are convenience defines to make the above
 * more readable.
 */

duk_push_string(ctx, "my_prop_1");
duk_push_int(ctx, 123);  /* prop value */
duk_def_prop(ctx,
             obj_idx,
             DUK_DEFPROP_HAVE_VALUE |
             DUK_DEFPROP_SET_WRITABLE |
             DUK_DEFPROP_CLEAR_ENUMERABLE |
             DUK_DEFPROP_SET_CONFIGURABLE);

/* Change the property value and make it non-writable.  Don't touch other
 * attributes.
 */

duk_push_string(ctx, "my_prop_1");
duk_push_int(ctx, 321);
duk_def_prop(ctx,
             obj_idx,
             DUK_DEFPROP_HAVE_VALUE |
             DUK_DEFPROP_HAVE_WRITABLE | 0);

/* Make the property non-configurable, don't touch value or other attributes. */

duk_push_string(ctx, "my_prop_1");
duk_def_prop(ctx,
             obj_idx,
             DUK_DEFPROP_HAVE_CONFIGURABLE | 0);

/* Create an accessor property which is non-configurable and non-enumerable.
 * Attribute flags are not given so they default to Ecmascript defaults
 * (false) automatically.
 */

duk_push_string(ctx, "my_accessor_1");
duk_push_c_function(ctx, my_getter, 0 /*nargs*/);
duk_push_c_function(ctx, my_setter, 1 /*nargs*/);
duk_def_prop(ctx,
             obj_idx,
             DUK_DEFPROP_HAVE_GETTER |
             DUK_DEFPROP_HAVE_SETTER);

/* Create an accessor property which is non-configurable but enumerable.
 * Attribute flags are given explicitly which is easier to read without
 * knowing about Ecmascript attribute default values.
 */

duk_push_string(ctx, "my_accessor_2");
duk_push_c_function(ctx, my_getter, 0 /*nargs*/);
duk_push_c_function(ctx, my_setter, 1 /*nargs*/);
duk_def_prop(ctx,
             obj_idx,
             DUK_DEFPROP_HAVE_GETTER |
             DUK_DEFPROP_HAVE_SETTER |
             DUK_DEFPROP_HAVE_CONFIGURABLE |  /* clear */
             DUK_DEFPROP_HAVE_ENUMERABLE | DUK_DEFPROP_ENUMERABLE);  /* set */

/* Change the value of a non-configurable property by force. */
duk_push_string(ctx, "my_nonconfigurable_prop");
duk_push_value(ctx, 321);
duk_def_prop(ctx,
             obj_idx,
             DUK_DEFPROP_HAVE_VALUE |
             DUK_DEFPROP_FORCE);

请参阅 §


.duk_del_prop() 1.0.0 property §

原型 §

duk_bool_t duk_del_prop(duk_context *ctx, duk_idx_t obj_idx);

堆栈 §

[ . . . obj . . . key ] [ . . . obj . . . ]

摘要 §

Delete the property key of a value at obj_idx. key is removed from the stack. Return code and error throwing behavior:

  • If property exists and is configurable (deletable), deletes the property and returns 1.
  • If property exists but is not configurable, throws an error (strict mode semantics).
  • If property does not exist, returns 1 (not 0).
  • If the value at obj_idx is not object coercible, throws an error.
  • If obj_idx is invalid, throws an error.

The property deletion is equivalent to the Ecmascript expression res = delete obj[key]. For precise semantics, see Property Accessors, The delete operator and [[Delete]] (P, Throw). The return value and error throwing behavior mirrors the Ecmascript delete operator behavior. Both the target value and the key are coerced:

  • The target value is automatically coerced to an object. However, this object is a temporary one, so deleting its properties is not very useful.
  • The key argument is internally coerced using ToPropertyKey() coercion which results in a string or a Symbol. There is an internal fast path for arrays and numeric indices which avoids an explicit string coercion, so use a numeric key when applicable.

If the target is a Proxy object which implements the deleteProperty trap, the trap is invoked and the API call return value matches the trap return value.

This API call returns 1 when the target property does not exist. This is not very intuitive, but follows Ecmascript semantics: delete obj.nonexistent also evaluates to true.

If the key is a fixed string you can avoid one API call and use the duk_del_prop_string() variant. Similarly, if the key is an array index, you can use the duk_del_prop_index() variant.

Although the base value for property accesses is usually an object, it can technically be an arbitrary value. Plain string and buffer values have virtual index properties so you can access "foo"[2], for instance. Most primitive values also inherit from some prototype object so that you can e.g. call methods on them: (12345).toString(16).

示例 §

duk_bool_t rc;

duk_push_string(ctx, "myProperty");
rc = duk_del_prop(ctx, -3);
printf("delete obj.myProperty -> rc=%d\n", (int) rc);

.duk_del_prop_index() 1.0.0 property §

原型 §

duk_bool_t duk_del_prop_index(duk_context *ctx, duk_idx_t obj_idx, duk_uarridx_t arr_idx);

堆栈 §

[ . . . obj . . . ] [ . . . obj . . . ]

摘要 §

Like duk_del_prop(), but the property name is given as an unsigned integer arr_idx. This is especially useful for deleting array elements (but is not limited to that).

Conceptually the number is coerced to a string for the property deletion, e.g. 123 would be equivalent to a property name "123". Duktape avoids an explicit coercion whenever possible.

示例 §

duk_bool_t rc;

rc = duk_del_prop_index(ctx, -3, 123);
printf("delete obj[123] -> rc=%d\n", (int) rc);

.duk_del_prop_lstring() 2.0.0 property §

原型 §

duk_bool_t duk_del_prop_lstring(duk_context *ctx, duk_idx_t obj_idx, const char *key, duk_size_t key_len);

堆栈 §

[ . . . obj . . . ] [ . . . obj . . . ]

摘要 §

Like duk_del_prop(), but the property name is given as a string with explicit length.

示例 §

duk_bool_t rc;

rc = duk_del_prop_lstring(ctx, -3, "internal" "\x00" "nul");
printf("delete obj.internal[00]nul -> rc=%d\n", (int) rc);

.duk_del_prop_string() 1.0.0 property §

原型 §

duk_bool_t duk_del_prop_string(duk_context *ctx, duk_idx_t obj_idx, const char *key);

堆栈 §

[ . . . obj . . . ] [ . . . obj . . . ]

摘要 §

Like duk_del_prop(), but the property name is given as a NUL-terminated C string key.

示例 §

duk_bool_t rc;

rc = duk_del_prop_string(ctx, -3, "propertyName");
printf("delete obj.propertyName -> rc=%d\n", (int) rc);

.duk_destroy_heap() 1.0.0 heap §

原型 §

void duk_destroy_heap(duk_context *ctx);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Destroy a Duktape heap. The argument context can be any context linked to the heap. All resources related to the heap are freed and must not be referenced after the call completes. These resources include all contexts linked to the heap, and also all string and buffer pointers within the heap.

If ctx is NULL, the call is a no-op.

示例 §

duk_destroy_heap(ctx);

.duk_dump_function() 1.3.0 stack bytecode §

原型 §

void duk_dump_function(duk_context *ctx);

堆栈 §

[ . . . function ] [ . . . bytecode ]

摘要 §

Dump an Ecmascript function at stack top into bytecode, replacing the function with a buffer containing the bytecode data. The bytecode can be loaded back using duk_load_function().

For more information on Duktape bytecode dump/load, supported features, and known limitations, see bytecode.rst. Duktape bytecode format is not intended for obfuscation, see notes on Obfuscation.

示例 §

duk_eval_string(ctx, "(function helloWorld() { print('hello world'); })");
duk_dump_function(ctx);
/* stack top now contains a buffer containing helloWorld bytecode */

请参阅 §


.duk_dup() 1.0.0 stack §

原型 §

void duk_dup(duk_context *ctx, duk_idx_t from_idx);

堆栈 §

[ . . . val . . . ] [ . . . val . . . val ]

摘要 §

Push a duplicate of value at from_idx to the stack. If from_idx is invalid, throws an error.

示例 §

duk_push_int(ctx, 123);  /* -> [ ... 123 ] */
duk_push_int(ctx, 234);  /* -> [ ... 123 234 ] */
duk_dup(ctx, -2);        /* -> [ ... 123 234 123 ] */

请参阅 §


.duk_dup_top() 1.0.0 stack §

原型 §

void duk_dup_top(duk_context *ctx);

堆栈 §

[ . . . val ] [ . . . val val ]

摘要 §

Push a duplicate of the value at stack top to the stack. If the value stack is empty, throws an error.

Equivalent to calling duk_dup(ctx, -1).

示例 §

duk_push_int(ctx, 123);  /* -> [ ... 123 ] */
duk_push_int(ctx, 234);  /* -> [ ... 123 234 ] */
duk_dup_top(ctx);        /* -> [ ... 123 234 234 ] */

.duk_enum() 1.0.0 property object §

原型 §

void duk_enum(duk_context *ctx, duk_idx_t obj_idx, duk_uint_t enum_flags);

堆栈 §

[ . . . obj . . . ] [ . . . obj . . . enum ]

摘要 §

Create an enumerator for object at obj_idx. Enumeration details can be controlled with enum_flags. If the target value is not an object, throws an error.

Enumeration flags:

DUK_ENUM_INCLUDE_NONENUMERABLE Enumerate also non-enumerable properties, by default only enumerable properties are enumerated
DUK_ENUM_INCLUDE_HIDDEN Enumerate also hidden Symbols, by default hidden Symbols are not enumerated. Use together with DUK_ENUM_INCLUDE_SYMBOLS. In Duktape 1.x this flag was called DUK_ENUM_INCLUDE_INTERNAL.
DUK_ENUM_INCLUDE_SYMBOLS Include Symbols in the enumeration result. Hidden Symbols are not included unless DUK_ENUM_INCLUDE_HIDDEN is specified.
DUK_ENUM_EXCLUDE_STRINGS Exclude strings from the enumeration result. By default strings are included.
DUK_ENUM_OWN_PROPERTIES_ONLY Enumerate only an object's "own" properties, by default also inherited properties are enumerated
DUK_ENUM_ARRAY_INDICES_ONLY Enumerate only array indices, i.e. property names of the form "0", "1", "2", etc
DUK_ENUM_SORT_ARRAY_INDICES Apply the ES2015 [[OwnPropertyKeys]] enumeration order over the whole enumeration result rather than per inheritance level, this has the effect of sorting array indices (even when inherited)
DUK_ENUM_NO_PROXY_BEHAVIOR Enumerate a Proxy object itself without invoking Proxy behaviors.

Without any flags the enumeration behaves like for-in: own and inherited enumerable properties are included, and enumeration order follows the Ecmascript ES2015 [[OwnPropertyKeys]] enumeration order, applied for each inheritance level.

Once the enumerator has been created, use duk_next() to extract keys (or key/value pairs) from the enumerator.

The ES2015 [[OwnPropertyKeys]] enumeration order is: (1) array indices in ascending order, (2) non-array-index keys in their insertion order, and (3) symbols in their insertion order. This rule is applied separately for each inheritance level, so that if array index keys are inherited, they will appear out-of-order in the result. For most practical code this is not an issue because array indices are very rarely inherited. You can force the whole enumeration sequence to be sorted using DUK_ENUM_SORT_ARRAY_INDICES.

示例 §

duk_enum(ctx, -3, DUK_ENUM_INCLUDE_NONENUMERABLE);

while (duk_next(ctx, -1 /*enum_idx*/, 0 /*get_value*/)) {
    /* [ ... enum key ] */
    printf("-> key %s\n", duk_get_string(ctx, -1));
    duk_pop(ctx);  /* pop_key */
}

duk_pop(ctx);  /* pop enum object */

请参阅 §


.duk_equals() 1.0.0 compare §

原型 §

duk_bool_t duk_equals(duk_context *ctx, duk_idx_t idx1, duk_idx_t idx2);

堆栈 §

[ . . . val1 . . . val2 . . . ]

摘要 §

Compare values at idx1 and idx2 for equality. Returns 1 if values are considered equal using Ecmascript Equals operator (==) semantics, otherwise returns 0. Also returns 0 if either index is invalid.

Because The Abstract Equality Comparison Algorithm used by the Equals operator performs value coercion (ToNumber() and ToPrimitive()), the comparison may have side effects and may throw an error. The strict equality comparison, available through duk_strict_equals(), has no side effects.

Comparison algorithm for Duktape custom types is described in Equality (non-strict).

示例 §

if (duk_equals(ctx, -3, -7)) {
    printf("values at indices -3 and -7 are equal\n");
}

请参阅 §


.duk_error() 1.0.0 error §

原型 §

duk_ret_t duk_error(duk_context *ctx, duk_errcode_t err_code, const char *fmt, ...);

堆栈 §

[ . . . ] [ . . . err ]

摘要 §

Push a new Error object to the stack and throw it. This call never returns.

The message property of the error object will be set to a sprintf-formatted string using fmt and the remaining arguments. The internal prototype for the created error object is chosen based on err_code. For instance, DUK_ERR_RANGE_ERROR causes the built-in RangeError prototype to be used. The valid range for user error codes is [1,16777215].

To push an Error object to the stack without throwing it, use duk_push_error_object().

Even though the function never returns, the prototype describes a return value which allows code such as:

if (argvalue < 0) {
    return duk_error(ctx, DUK_ERR_TYPE_ERROR, "invalid argument value: %d", (int) argvalue);
}

示例 §

duk_error(ctx, DUK_ERR_RANGE_ERROR, "argument out of range: %d", (int) argval);

.duk_error_va() 1.1.0 vararg error §

原型 §

duk_ret_t duk_error_va(duk_context *ctx, duk_errcode_t err_code, const char *fmt, va_list ap);

堆栈 §

[ . . . ] [ . . . err ]

摘要 §

Vararg variant of duk_error().

示例 §

void my_range_error(duk_context *ctx, const char *fmt, ...) {
    va_list ap;

    va_start(ap, fmt);
    duk_error_va(ctx, DUK_ERR_RANGE_ERROR, fmt, ap);
    va_end(ap);
}

.duk_eval() 1.0.0 compile §

原型 §

void duk_eval(duk_context *ctx);

堆栈 §

[ . . . source ] [ . . . result ]

摘要 §

Evaluate the Ecmascript source code at the top of the stack, and leave a single return value on top of the stack. May throw an error, errors are not caught automatically. The filename associated with the temporary eval function is "eval".

This is essentially a shortcut for:

duk_push_string(ctx, "eval");
duk_compile(ctx, DUK_COMPILE_EVAL);  /* [ ... source filename ] -> [ function ] */
duk_call(ctx, 0);

The source code is evaluated in non-strict mode unless it contains an explicit "use strict" directive. In particular, strictness of the current context is not transferred into the eval code. This avoids confusing behavior where eval strictness would depend on whether eval is used inside a Duktape/C function call (strict mode) or outside of one (non-strict mode).

If the eval input is a fixed string, you can also use duk_eval_string().

示例 §

/* Eval result in Ecmascript is the last non-empty statement; here, the
 * result of the eval is the number 123.
 */

duk_push_string(ctx, "print('Hello world!'); 123;");
duk_eval(ctx);
printf("return value is: %lf\n", (double) duk_get_number(ctx, -1));
duk_pop(ctx);

.duk_eval_error() 2.0.0 error §

原型 §

duk_ret_t duk_eval_error(duk_context *ctx, const char *fmt, ...);

堆栈 §

[ . . . ] [ . . . err ]

摘要 §

Convenience API call, equivalent to duk_error() with an error code DUK_ERR_EVAL_ERROR.

示例 §

return duk_eval_error(ctx, "my error: %d", (int) argval);

请参阅 §


.duk_eval_error_va() 2.0.0 vararg error §

原型 §

duk_ret_t duk_eval_error_va(duk_context *ctx, const char *fmt, va_list ap);

堆栈 §

[ . . . ] [ . . . err ]

摘要 §

Convenience API call, equivalent to duk_error_va() with an error code DUK_ERR_EVAL_ERROR.

示例 §

void my_eval_error(duk_context *ctx, const char *fmt, ...) {
    va_list ap;

    va_start(ap, fmt);
    duk_eval_error_va(ctx, fmt, ap);
    va_end(ap);
}

请参阅 §


.duk_eval_lstring() 1.0.0 compile §

原型 §

void duk_eval_lstring(duk_context *ctx, const char *src, duk_size_t len);

堆栈 §

[ . . . ] [ . . . result ]

摘要 §

Like duk_eval(), but the eval input is given as a C string with explicit length. The filename associated with the temporary eval function is "eval".

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

const char *src = /* ... */;
duk_size_t len = /* ... */;

duk_eval_lstring(ctx, src, len);
printf("result is: %s\n", duk_get_string(ctx, -1));
duk_pop(ctx);

.duk_eval_lstring_noresult() 1.0.0 compile §

原型 §

void duk_eval_lstring_noresult(duk_context *ctx, const char *src, duk_size_t len);

堆栈 §

[ . . . ] [ . . . ]

摘要 §

Like duk_eval_lstring(), but leaves no result on the value stack.

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

const char *src = /* ... */;
duk_size_t len = /* ... */;

duk_eval_lstring_noresult(ctx, src, len);

.duk_eval_noresult() 1.0.0 compile §

原型 §

void duk_eval_noresult(duk_context *ctx);

堆栈 §

[ . . . source ] [ . . . ]

摘要 §

Like duk_eval(), but leaves no result on the value stack.

示例 §

duk_push_string(ctx, "print('Hello world!');");
duk_eval_noresult(ctx);

.duk_eval_string() 1.0.0 compile §

原型 §

void duk_eval_string(duk_context *ctx, const char *src);

堆栈 §

[ . . . ] [ . . . result ]

摘要 §

Like duk_eval(), but the eval input is given as a C string. The filename associated with the temporary eval function is "eval".

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

duk_eval_string(ctx, "'testString'.toUpperCase()");
printf("result is: %s\n", duk_get_string(ctx, -1));
duk_pop(ctx);

.duk_eval_string_noresult() 1.0.0 compile §

原型 §

void duk_eval_string_noresult(duk_context *ctx, const char *src);

堆栈 §

[ . . . ] [ . . . ]

摘要 §

Like duk_eval_string(), but leaves no result on the value stack.

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

duk_eval_string_noresult(ctx, "print('testString'.toUpperCase())");

.duk_fatal() 1.0.0 error §

原型 §

duk_ret_t duk_fatal(duk_context *ctx, const char *err_msg);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Call fatal error handler with an optional message (err_msg may be NULL). Like all strings in Duktape, the error message should be an UTF-8 string, although pure ASCII is strongly recommended.

A fatal error handler never returns and may e.g. exit the current process. Error catching points (like try-catch statements and error catching API calls) are bypassed, and finalizers are not executed. You should only call this function when a truly fatal, unrecoverable error has occurred.

Even though the function never returns, the prototype describes a return value which allows code such as:

if (argvalue < 0) {
    return duk_fatal(ctx, "argvalue invalid, cannot continue execution");
}

示例 §

duk_fatal(ctx, "assumption failed");

.duk_free() 1.0.0 memory §

原型 §

void duk_free(duk_context *ctx, void *ptr);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Like duk_free_raw() but may involve garbage collection steps. The garbage collection interaction cannot cause the operation to fail.

duk_free() can be used to free memory allocated with either duk_alloc() or duk_alloc_raw() and their reallocation variants.

Currently a duk_free() cannot cause a garbage collection pass but does update internal GC trigger counters.

示例 §

void *buf = duk_alloc(ctx, 1024);
/* ... */

duk_free(ctx, buf);  /* safe even if 'buf' is NULL */

请参阅 §


.duk_free_raw() 1.0.0 memory §

原型 §

void duk_free_raw(duk_context *ctx, void *ptr);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Free memory allocated with the allocation function registered to the context. The operation cannot fail. If ptr is NULL, the call is a no-op.

duk_free_raw() can be used to free memory allocated with either duk_alloc() or duk_alloc_raw() and their reallocation variants.

示例 §

void *buf = duk_alloc_raw(ctx, 1024);
/* ... */

duk_free_raw(ctx, buf);  /* safe even if 'buf' is NULL */

请参阅 §


.duk_gc() 1.0.0 memory heap §

原型 §

void duk_gc(duk_context *ctx, duk_uint_t flags);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Force a mark-and-sweep garbage collection round. If mark-and-sweep is disabled in the Duktape build, the call is a no-op.

The following flags are defined:

DefineDescription
DUK_GC_COMPACTForce object property table compaction

You may want to call this function twice to ensure even objects with finalizers are collected. Currently it takes two mark-and-sweep rounds to collect such objects. First round marks the object as finalizable and runs the finalizer. Second round ensures the object is still unreachable after finalization and then frees the object.

示例 §

duk_gc(ctx, 0);

.duk_generic_error() 2.0.0 error §

原型 §

duk_ret_t duk_generic_error(duk_context *ctx, const char *fmt, ...);

堆栈 §

[ . . . ] [ . . . err ]

摘要 §

Convenience API call, equivalent to duk_error() with an error code DUK_ERR_ERROR.

示例 §

return duk_generic_error(ctx, "my error: %d", (int) argval);

请参阅 §


.duk_generic_error_va() 2.0.0 vararg error §

原型 §

duk_ret_t duk_generic_error_va(duk_context *ctx, const char *fmt, va_list ap);

堆栈 §

[ . . . ] [ . . . err ]

摘要 §

Convenience API call, equivalent to duk_error_va() with an error code DUK_ERR_ERROR.

示例 §

void my_generic_error(duk_context *ctx, const char *fmt, ...) {
    va_list ap;

    va_start(ap, fmt);
    duk_generic_error_va(ctx, fmt, ap);
    va_end(ap);
}

请参阅 §


.duk_get_boolean() 1.0.0 stack §

原型 §

duk_bool_t duk_get_boolean(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Get the boolean value at idx without modifying or coercing the value. Returns 1 if the value is true, 0 if the value is false, not a boolean, or the index is invalid.

Note that the value is not coerced, so even a "truthy" Ecmascript value (like a non-empty string) will be treated as false. If you want to coerce the value, use duk_to_boolean().

示例 §

if (duk_get_boolean(ctx, -3)) {
    printf("value is true\n");
}

.duk_get_buffer() 1.0.0 stack buffer §

原型 §

void *duk_get_buffer(duk_context *ctx, duk_idx_t idx, duk_size_t *out_size);

堆栈 §

[ . . . val . . . ]

摘要 §

Get the data pointer for a (plain) buffer value at idx without modifying or coercing the value. Returns a non-NULL pointer if the value is a valid buffer with a non-zero size. For a zero-size buffer, may return a NULL or a non-NULL pointer. Returns NULL if the value is not a buffer or the index is invalid. If out_size is non-NULL, the size of the buffer is written to *out_size; 0 is written if the return value is NULL.

If the target value is a fixed buffer, the returned pointer is stable and won't change during the lifetime of the buffer. For dynamic and external buffers the pointer may change as the buffer is resized or reconfigured; the caller is responsible for ensuring pointer values returned from this API call are not used after the buffer is resized/reconfigured.

There is no reliable way to distinguish a zero-size buffer from a non-buffer based on the return values alone: a NULL with zero size is returned for a non-buffer. The same values may be returned for a zero-size buffer (although it is also possible that a non-NULL pointer is returned). Use duk_is_buffer_data() when type checking a buffer or a buffer object.

示例 §

void *ptr;
duk_size_t sz;

ptr = duk_get_buffer(ctx, -3, &sz);
printf("buf=%p, size=%lu\n", ptr, (unsigned long) sz);

.duk_get_buffer_data() 1.3.0 stack bufferobject buffer §

原型 §

void *duk_get_buffer_data(duk_context *ctx, duk_idx_t idx, duk_size_t *out_size);

堆栈 §

[ . . . val . . . ]

摘要 §

Get the data pointer for a plain buffer or a buffer object (ArrayBuffer, Node.js Buffer, DataView, or TypedArray view) value at idx without modifying or coercing the value. Return a non-NULL pointer if the value is a valid buffer with a non-zero size. For a zero-size buffer, may return a NULL or a non-NULL pointer. Returns NULL if the value is not a buffer, the value is a buffer object whose "backing buffer" doesn't fully cover the buffer object's apparent size, or the index is invalid. If out_size is non-NULL, the size of the buffer is written to *out_size; 0 is written if the return value is NULL.

The data area indicated by the return pointer and length is the full buffer for a plain buffer value, and the active "slice" for a buffer object. The length returned is expressed in bytes (instead of elements), so that you can always access ptr[0] to ptr[len - 1]. For example:

  • For new Uint8Array(16) the return pointer would point to start of the array and length would be 16.
  • For new Uint32Array(16) the return pointer would point to start of the array and length would be 64.
  • For new Uint32Array(16).subarray(2, 6) the return pointer would point to the start of the subarray (2 x 4 = 8 bytes from the start of the Uint32Array) and length would be 16 ((6-2) x 4).

If the target value or the underlying buffer value of a buffer object is a fixed buffer, the returned pointer is stable and won't change during the lifetime of the buffer. For dynamic and external buffers the pointer may change as the buffer is resized or reconfigured; the caller is responsible for ensuring pointer values returned from this API call are not used after the buffer is resized/reconfigured. Buffers created from Ecmascript code directly e.g. as new Buffer(8) are backed by an automatic fixed buffer, so their pointers are always stable.

In special cases it's possible that a buffer object is backed by a plain buffer which is smaller than the buffer object's apparent size. In these cases a NULL is returned; this ensures that the pointer and size returned can always be used safely. (This behavior may change even in minor versions.)

There is no reliable way to distinguish a zero-size buffer from a non-buffer based on the return values alone: a NULL with zero size is returned for a non-buffer. The same values may be returned for a zero-size buffer (although it is also possible that a non-NULL pointer is returned). Use duk_is_buffer_data() when type checking a buffer or a buffer object.

示例 §

void *ptr;
duk_size_t sz;

duk_eval_string(ctx, "new Uint16Array(16)");
ptr = duk_get_buffer_data(ctx, -1, &sz);

/* Here 'ptr' would be non-NULL and sz would be 32 (bytes). */

.duk_get_c_function() 1.0.0 stack function §

原型 §

duk_c_function duk_get_c_function(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Get the Duktape/C function pointer (a duk_c_function) from an Ecmascript function object associated with a Duktape/C function. If the value is not such a function or idx is invalid, returns NULL.

If you prefer an error to be thrown for an invalid value or index, use duk_require_c_function().

示例 §

duk_c_function funcptr;

funcptr = duk_get_c_function(ctx, -3);

.duk_get_context() 1.0.0 stack borrowed §

原型 §

duk_context *duk_get_context(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Get a context pointer for a Duktape thread at idx. If the value at idx is not a Duktape thread or the index is invalid, returns NULL.

The returned context pointer is only valid while the Duktape thread is reachable from a garbage collection point of view.

If you prefer an error to be thrown for an invalid value or index, use duk_require_context().

示例 §

duk_context *new_ctx;

/* Create a new thread and get a context pointer. */

(void) duk_push_thread(ctx);
new_ctx = duk_get_context(ctx, -1);

/* You can use new_ctx as long as the related thread is reachable
 * from a garbage collection point of view.
 */

duk_push_string(new_ctx, "foo");

/* This duk_pop() makes the new thread unreachable (assuming there
 * is no other reference to it), so new_ctx is no longer valid
 * afterwards.
 */

duk_pop(ctx);

/* Using new_ctx here may cause a crash. */

.duk_get_current_magic() 1.0.0 magic function §

原型 §

duk_int_t duk_get_current_magic(duk_context *ctx);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Get the 16-bit signed "magic" value associated with the running Duktape/C function. If there is no current activation, zero is returned.

The magic function allows the same Duktape/C function to be used with slightly different behavior; behavior flags or other parameters can be passed in the magic field. This is less expensive than having behavior related flags or properties in the function object as normal properties.

If you need an unsigned 16-bit value, simply AND the result:

unsigned int my_flags = ((unsigned int) duk_get_current_magic(ctx)) & 0xffffU;

示例 §

duk_int_t my_flags = duk_get_current_magic(ctx);
if (my_flags & 0x01) {
    printf("flag set\n");
} else {
    printf("flag not set\n");
}

.duk_get_error_code() 1.1.0 stack error §

原型 §

duk_errcode_t duk_get_error_code(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Map the value at idx to the error codes DUK_ERR_xxx based on which Error subclass the value inherits from. For example, if the value at the stack top is an user-defined error which inherits from ReferenceError, the return value will be DUK_ERR_REFERENCE_ERROR. If the value inherits from Error but doesn't inherit from any of the standard subclasses (EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError) DUK_ERR_ERROR is returned. If the value is not an object, does not inherit from Error, or idx is invalid, returns 0 (= DUK_ERR_NONE).

示例 §

if (duk_get_error_code(ctx, -3) == DUK_ERR_URI_ERROR) {
    printf("Invalid URI\n");
}

.duk_get_finalizer() 1.0.0 object finalizer §

原型 §

void duk_get_finalizer(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ] [ . . . val . . . finalizer ]

摘要 §

Get the finalizer associated with a value at idx. If the value is not an object or it is an object without a finalizer, undefined is pushed to the stack instead.

示例 §

/* Get the finalizer of an object at index -3. */
duk_get_finalizer(ctx, -3);

请参阅 §


.duk_get_global_lstring() 2.0.0 property §

原型 §

duk_bool_t duk_get_global_lstring(duk_context *ctx, const char *key, duk_size_t key_len);

堆栈 §

[ . . . ] [ . . . val ] (if key exists)
[ . . . ] [ . . . undefined ] (if key doesn't exist)

摘要 §

Like duk_get_global_string() but the key is given as a string with explicit length.

示例 §

(void) duk_get_global_lstring(ctx, "internal" "\x00" "nul");

.duk_get_global_string() 1.0.0 property §

原型 §

duk_bool_t duk_get_global_string(duk_context *ctx, const char *key);

堆栈 §

[ . . . ] [ . . . val ] (if key exists)
[ . . . ] [ . . . undefined ] (if key doesn't exist)

摘要 §

Get property named key from the global object. Returns non-zero if the property exists and zero otherwise. This is a convenience function which does the equivalent of:

duk_bool_t ret;

duk_push_global_object(ctx);
ret = duk_get_prop_string(ctx, -1, key);
duk_remove(ctx, -2);
/* 'ret' would be the return value from duk_get_global_string() */

示例 §

(void) duk_get_global_string(ctx, "encodeURIComponent");
duk_push_string(ctx, "foo bar");
duk_call(ctx, 1);  /* [ ... encodeURIComponent "foo bar" ] -> [ "foo%20bar" ] */
printf("encoded: %s\n", duk_to_string(ctx, -1));
duk_pop(ctx);

.duk_get_heapptr() 1.1.0 stack borrowed §

原型 §

void *duk_get_heapptr(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Get a borrowed void * reference to a Duktape heap allocated value (object, buffer, string) at idx. Return NULL if the index is invalid or the target value is not heap allocated. The returned pointer must not be interpreted or dereferenced, but duk_push_heapptr() can be used to push the original value into the value stack later.

The returned void pointer is only valid while the original value is reachable from a garbage collection point of view. If this is not the case, it is memory unsafe to use duk_push_heapptr().

示例 §

duk_context *new_ctx;
void *ptr;

duk_eval_string(ctx, "({ foo: 'bar' })");
ptr = duk_get_heapptr(ctx, -1);

/* The original value must remain reachable for Duktape up to a future
 * duk_push_heapptr().  Here we just write it to the global object, but
 * it could also be a value stack somewhere, a stash object, etc.
 */
duk_put_global_string(ctx, "ref");

/* Later, assuming the original value has been reachable all the way
 * to here:
 */

duk_push_heapptr(ctx, ptr);
duk_get_prop_string(ctx, -1, "foo");
printf("obj.foo: %s\n", duk_safe_to_string(ctx, -1));  /* prints 'bar' */

.duk_get_int() 1.0.0 stack §

原型 §

duk_int_t duk_get_int(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Get the number at idx and convert it to a C duk_int_t by first clamping the value between [DUK_INT_MIN, DUK_INT_MAX] and then truncating towards zero. The value on the stack is not modified. If the value is a NaN, is not a number, or the index is invalid, returns 0.

Conversion examples:

InputOutput
-InfinityDUK_INT_MIN
DUK_INT_MIN - 1DUK_INT_MIN
-3.9-3
3.93
DUK_INT_MAX + 1DUK_INT_MAX
+InfinityDUK_INT_MAX
NaN0
"123"0 (non-number)
The coercion is different from a basic C cast from double to integer, which may have counterintuitive (and non-portable) behavior like coercing NaN to DUK_INT_MIN. The coercion is also different from Ecmascript ToInt32() coercion because the full range of the native duk_int_t is allowed (which may be more than 32 bits).

示例 §

printf("int value: %ld\n", (long) duk_get_int(ctx, -3));

.duk_get_length() 1.0.0 stack §

原型 §

duk_size_t duk_get_length(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Get a type-specific "length" for value at idx:

  • String: character length of string (not byte length)
  • Object: Math.floor(ToNumber(obj.length)) if result within duk_size_t unsigned range; otherwise 0
  • Buffer: byte length of buffer
  • Other type or invalid stack index: 0

To get the byte length of a string, use duk_get_lstring().

示例 §

if (duk_is_string(ctx, -3)) {
    printf("string char len is %lu\n", (unsigned long) duk_get_length(ctx, -3));
}

请参阅 §


.duk_get_lstring() 1.0.0 stack §

原型 §

const char *duk_get_lstring(duk_context *ctx, duk_idx_t idx, duk_size_t *out_len);

堆栈 §

[ . . . val . . . ]

摘要 §

Get character data pointer and length for a string at idx without modifying or coercing the value. Returns a non-NULL pointer to the read-only, NUL-terminated string data, and writes the string byte length to *out_len (if out_len is non-NULL). Returns NULL and writes zero to *out_len (if out_len is non-NULL) if the value is not a string or the index is invalid.

To get the string character length (instead of byte length), use duk_get_length().

A non-NULL return value is guaranteed even for zero length strings; this differs from how buffer data pointers are handled (for technical reasons).

示例 §

const char *buf;
duk_size_t len;

buf = duk_get_lstring(ctx, -3, &len);
if (buf) {
    printf("value is a string, %lu bytes\n", (unsigned long) len);
}

.duk_get_magic() 1.0.0 magic function §

原型 §

duk_int_t duk_get_magic(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Get the 16-bit signed "magic" value associated with the Duktape/C function at idx. If the value is not a Duktape/C function, an error is thrown.

Lightweight functions have space for only 8 magic value bits which is interpreted as a signed integer (-128 to 127).

示例 §

duk_int_t my_flags = duk_get_magic(ctx, -3);

.duk_get_memory_functions() 1.0.0 memory heap §

原型 §

void duk_get_memory_functions(duk_context *ctx, duk_memory_functions *out_funcs);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Get the memory management functions used by the context.

Normally there is no reason to call this function: you can use the memory management primitives through wrapped memory management functions such as duk_alloc(), duk_realloc(), and duk_free().

示例 §

duk_memory_functions funcs;

duk_get_memory_functions(ctx, &funcs);

.duk_get_now() 2.0.0 time experimental §

原型 §

duk_double_t duk_get_now(duk_context *ctx);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Get current time in POSIX milliseconds, as seen by the Ecmascript environment. The return value matches Date.now() with the reservation that sub-millisecond resolution may be available.

示例 §

duk_double_t now;

now = duk_get_now(ctx);
print("timestamp: %lf\n", (double) now);

.duk_get_number() 1.0.0 §

原型 §

duk_double_t duk_get_number(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Get the number value at idx without modifying or coercing the value. Returns NaN if the value is not a number or the index is invalid.

示例 §

printf("value: %lf\n", (double) duk_get_number(ctx, -3));

.duk_get_pointer() 1.0.0 stack §

原型 §

void *duk_get_pointer(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Get the pointer value at idx as void * without modifying or coercing the value. Returns NULL if the value is not a pointer or the index is invalid.

示例 §

void *ptr;

ptr = duk_get_pointer(ctx, -3);
printf("my pointer is: %p\n", ptr);

.duk_get_prop() 1.0.0 property §

原型 §

duk_bool_t duk_get_prop(duk_context *ctx, duk_idx_t obj_idx);

堆栈 §

[ . . . obj . . . key ] [ . . . obj . . . val ] (if key exists)
[ . . . obj . . . key ] [ . . . obj . . . undefined ] (if key doesn't exist)

摘要 §

Get the property key of a value at obj_idx. Return code and error throwing behavior:

  • If the property exists, 1 is returned and key is replaced by the property value on the value stack. However, if the property is an accessor, the "getter" function may throw an error.
  • If the property does not exist, 0 is returned and key is replaced by undefined on the value stack.
  • If the value at obj_idx is not object coercible, throws an error.
  • If obj_idx is invalid, throws an error.

The property read is equivalent to the Ecmascript expression res = obj[key] with the exception that the presence or absence of the property is indicated by the call return value. For precise semantics, see Property Accessors, GetValue (V), and [[Get]] (P). Both the target value and the key are coerced:

  • The target value is automatically coerced to an object. For instance, a string is converted to a String and you can access its "length" property.
  • The key argument is internally coerced using ToPropertyKey() coercion which results in a string or a Symbol. There is an internal fast path for arrays and numeric indices which avoids an explicit string coercion, so use a numeric key when applicable.

If the target is a Proxy object which implements the get trap, the trap is invoked and the API call always returns 1 (i.e. property present): the absence/presence of properties is not indicated by the get Proxy trap. Thus, the API call return value may be of limited use if the target object is potentially a Proxy.

If the key is a fixed string you can avoid one API call and use the duk_get_prop_string() variant. Similarly, if the key is an array index, you can use the duk_get_prop_index() variant.

Although the base value for property accesses is usually an object, it can technically be an arbitrary value. Plain string and buffer values have virtual index properties so you can access "foo"[2], for instance. Most primitive values also inherit from some prototype object so that you can e.g. call methods on them: (12345).toString(16).

示例 §

/* reading [global object].Math.PI */
duk_push_global_object(ctx);    /* -> [ global ] */
duk_push_string(ctx, "Math");   /* -> [ global "Math" ] */
duk_get_prop(ctx, -2);          /* -> [ global Math ] */
duk_push_string(ctx, "PI");     /* -> [ global Math "PI" ] */
duk_get_prop(ctx, -2);          /* -> [ global Math PI ] */
printf("Math.PI is %lf\n", (double) duk_get_number(ctx, -1));
duk_pop_n(ctx, 3);

/* reading a configuration value, cfg_idx is normalized
 * index of a configuration object.
 */
duk_push_string(ctx, "mySetting");
if (duk_get_prop(ctx, cfg_idx)) {
    const char *str_value = duk_to_string(ctx, -1);
    printf("configuration setting present, value: %s\n", str_value);
} else {
    printf("configuration setting missing\n");
}
duk_pop(ctx);  /* remember to pop, regardless of whether or not present */

.duk_get_prop_desc() 2.0.0 sandbox property §

原型 §

void duk_get_prop_desc(duk_context *ctx, duk_idx_t obj_idx, duk_uint_t flags);

堆栈 §

[ . . . obj . . . key ] [ . . . obj . . . desc ] (if property exists)
[ . . . obj . . . key ] [ . . . obj . . . undefined ] (if property doesn't exist)

摘要 §

Equivalent of Object.getOwnPropertyDescriptor() in the C API: pushes a property descriptor object for a named property of the object at obj_idx. If the target is not an object (or the index is invalid) an error is thrown.

No flags are defined yet, use 0 for flags.

示例 §

duk_idx_t obj_idx = /* ... */;

/* Check if property "my_prop" is a getter. */

duk_push_string(ctx, "my_prop");
duk_get_prop_desc(ctx, obj_idx, 0 /*flags*/);
if (duk_is_object(ctx, -1)) {
  /* Property found. */
  if (duk_has_prop_string(ctx, -1, "get")) {
    printf("my_prop is a getter\n");
  } else {
    printf("my_prop is not a getter\n");
  }
} else {
  printf("my_prop not found\n");
}

请参阅 §


.duk_get_prop_index() 1.0.0 property §

原型 §

duk_bool_t duk_get_prop_index(duk_context *ctx, duk_idx_t obj_idx, duk_uarridx_t arr_idx);

堆栈 §

[ . . . obj . . . ] [ . . . obj . . . val ] (if key exists)
[ . . . obj . . . ] [ . . . obj . . . undefined ] (if key doesn't exist)

摘要 §

Like duk_get_prop(), but the property name is given as an unsigned integer arr_idx. This is especially useful for accessing array elements (but is not limited to that).

Conceptually the number is coerced to a string for the property read, e.g. 123 would be equivalent to a property name "123". Duktape avoids an explicit coercion whenever possible.

示例 §

duk_get_prop_index(ctx, -3, 123);
printf("obj[123] = %s\n", duk_to_string(ctx, -1));
duk_pop(ctx);

.duk_get_prop_lstring() 2.0.0 property §

原型 §

duk_bool_t duk_get_prop_lstring(duk_context *ctx, duk_idx_t obj_idx, const char *key, duk_size_t key_len);

堆栈 §

[ . . . obj . . . ] [ . . . obj . . . val ] (if key exists)
[ . . . obj . . . ] [ . . . obj . . . undefined ] (if key doesn't exist)

摘要 §

Like duk_get_prop(), but the property name is given as a string with explicit length.

示例 §

duk_get_prop_lstring(ctx, -3, "internal" "\x00" "nul", 12);
printf("obj.propertyName = %s\n", duk_to_string(ctx, -1));
duk_pop(ctx);

.duk_get_prop_string() 1.0.0 property §

原型 §

duk_bool_t duk_get_prop_string(duk_context *ctx, duk_idx_t obj_idx, const char *key);

堆栈 §

[ . . . obj . . . ] [ . . . obj . . . val ] (if key exists)
[ . . . obj . . . ] [ . . . obj . . . undefined ] (if key doesn't exist)

摘要 §

Like duk_get_prop(), but the property name is given as a NUL-terminated C string key.

示例 §

duk_get_prop_string(ctx, -3, "propertyName");
printf("obj.propertyName = %s\n", duk_to_string(ctx, -1));
duk_pop(ctx);

.duk_get_prototype() 1.0.0 prototype object §

原型 §

void duk_get_prototype(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ] [ . . . val . . . proto ]

摘要 §

Get the internal prototype of the value at idx. If the value is not an object, an error is thrown. If the object has no prototype (which is possible for "naked objects") undefined is pushed to the stack instead.

示例 §

/* Get the internal prototype of an object at index -3. */
duk_get_prototype(ctx, -3);

请参阅 §


.duk_get_string() 1.0.0 string stack §

原型 §

const char *duk_get_string(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Get character data pointer for a string at idx without modifying or coercing the value. Returns a non-NULL pointer to the read-only, NUL-terminated string data. Returns NULL if the value is not a string or the index is invalid.

To get the string byte length explicitly (which is useful if the string contains embedded NUL characters), use duk_get_lstring().

A non-NULL return value is guaranteed even for zero length strings; this differs from how buffer data pointers are handled (for technical reasons).
Symbol values are visible in the C API as strings so that both duk_is_symbol() and duk_is_string() are true. This behavior is similar to Duktape 1.x internal strings. Symbols are still an experimental feature; for now, you can distinguish Symbols from ordinary strings using duk_is_symbol(). For the internal representation, see symbols.rst.

示例 §

const char *buf;

buf = duk_get_string(ctx, -3);
if (buf) {
    printf("value is a string: %s\n", buf);
}

.duk_get_top() 1.0.0 stack §

原型 §

duk_idx_t duk_get_top(duk_context *ctx);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Get current stack top (>= 0), indicating the number of values currently on the value stack (of the current activation).

示例 §

printf("stack top is %ld\n", (long) duk_get_top(ctx));

.duk_get_top_index() 1.0.0 stack §

原型 §

duk_idx_t duk_get_top_index(duk_context *ctx);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Get the absolute index (>= 0) of the topmost value on the stack. If the stack is empty, returns DUK_INVALID_INDEX.

示例 §

duk_idx_t idx_top;

idx_top = duk_get_top_index(ctx);
if (idx_top == DUK_INVALID_INDEX) {
    printf("stack is empty\n");
} else {
    printf("index of top element: %ld\n", (long) idx_top);
}

.duk_get_type() 1.0.0 stack §

原型 §

duk_int_t duk_get_type(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns type of value at idx. The return value is one of DUK_TYPE_xxx or DUK_TYPE_NONE if idx is invalid.

Symbol values are visible in the C API as strings so that both duk_is_symbol() and duk_is_string() are true. This behavior is similar to Duktape 1.x internal strings. Symbols are still an experimental feature; for now, you can distinguish Symbols from ordinary strings using duk_is_symbol(). For the internal representation, see symbols.rst.

示例 §

if (duk_get_type(ctx, -3) == DUK_TYPE_NUMBER) {
    printf("value is a number\n");
}

.duk_get_type_mask() 1.0.0 stack §

原型 §

duk_uint_t duk_get_type_mask(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns type mask of value at idx. The return value is one of DUK_TYPE_MASK_xxx or DUK_TYPE_MASK_NONE if idx is invalid.

Type masks allow e.g. for a convenient comparison for multiple types at once (the duk_check_type_mask() call is even more convenient for this purpose).

Symbol values are visible in the C API as strings so that both duk_is_symbol() and duk_is_string() are true. This behavior is similar to Duktape 1.x internal strings. Symbols are still an experimental feature; for now, you can distinguish Symbols from ordinary strings using duk_is_symbol(). For the internal representation, see symbols.rst.

示例 §

if (duk_get_type_mask(ctx, -3) & (DUK_TYPE_MASK_STRING |
                                  DUK_TYPE_MASK_NUMBER)) {
    printf("value is a string or a number\n");
}

.duk_get_uint() 1.0.0 stack §

原型 §

duk_uint_t duk_get_uint(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Get the number at idx and convert it to a C duk_uint_t by first clamping the value between [0, DUK_UINT_MAX] and then truncating towards zero. The value on the stack is not modified. If the value is a NaN, is not a number, or the index is invalid, returns 0.

Conversion examples:

InputOutput
-Infinity0
-10
-3.90
3.93
DUK_UINT_MAX + 1DUK_UINT_MAX
+InfinityDUK_UINT_MAX
NaN0
"123"0 (non-number)
The coercion is different from a basic C cast from double to unsigned integer, which may have counterintuitive (and non-portable) behavior for e.g. NaN values. The coercion is also different from Ecmascript ToUint32() coercion because the full range of the native duk_uint_t is allowed (which may be more than 32 bits).

示例 §

printf("unsigned int value: %lu\n", (unsigned long) duk_get_uint(ctx, -3));

.duk_has_prop() 1.0.0 stack property §

原型 §

duk_bool_t duk_has_prop(duk_context *ctx, duk_idx_t obj_idx);

堆栈 §

[ . . . obj . . . key ] [ . . . obj . . . ]

摘要 §

Check whether value at obj_idx has a property key. key is removed from the stack. Return code and error throwing behavior:

  • If the property exists, 1 is returned.
  • If the property doesn't exist, 0 is returned.
  • If the value at obj_idx is not an object, throws an error.
  • If obj_idx is invalid, throws an error.

The property existence check is equivalent to the Ecmascript expression res = key in obj. For semantics, see Property Accessors, The in operator, and [[HasProperty]] (P). Both the target value and the key are coerced:

  • The target value is automatically coerced to an object. For instance, a string is converted to a String and you can check for its "length" property.
  • The key argument is internally coerced using ToPropertyKey() coercion which results in a string or a Symbol. There is an internal fast path for arrays and numeric indices which avoids an explicit string coercion, so use a numeric key when applicable.

If the target is a Proxy object which implements the has trap, the trap is invoked and the API call return value matches the trap return value.

Instead of accepting any object coercible value (like most property related API calls) this call accepts only an object as its target value. This is intentional as it follows Ecmascript operator semantics.

If the key is a fixed string you can avoid one API call and use the duk_has_prop_string() variant. Similarly, if the key is an array index, you can use the duk_has_prop_index() variant.

Although the base value for property accesses is usually an object, it can technically be an arbitrary value. Plain string and buffer values have virtual index properties so you can access "foo"[2], for instance. Most primitive values also inherit from some prototype object so that you can e.g. call methods on them: (12345).toString(16).

示例 §

duk_push_string(ctx, "myProperty");
if (duk_has_prop(ctx, -3)) {
    printf("obj has 'myProperty'\n");
} else {
    printf("obj does not have 'myProperty'\n");
}

.duk_has_prop_index() 1.0.0 stack property §

原型 §

duk_bool_t duk_has_prop_index(duk_context *ctx, duk_idx_t obj_idx, duk_uarridx_t arr_idx);

堆栈 §

[ . . . obj . . . ] [ . . . obj . . . ]

摘要 §

Like duk_has_prop(), but the property name is given as an unsigned integer arr_idx. This is especially useful for checking existence of array elements (but is not limited to that).

Conceptually the number is coerced to a string for property existence check, e.g. 123 would be equivalent to a property name "123". Duktape avoids an explicit coercion whenever possible.

示例 §

if (duk_has_prop_index(ctx, -3, 123)) {
    printf("obj has index 123\n");
} else {
    printf("obj does not have index 123\n");
}

.duk_has_prop_lstring() 2.0.0 stack property §

原型 §

duk_bool_t duk_has_prop_lstring(duk_context *ctx, duk_idx_t obj_idx, const char *key, duk_size_t key_len);

堆栈 §

[ . . . obj . . . ] [ . . . obj . . . ]

摘要 §

Like duk_has_prop(), but the property name is given as a string with explicit length.

示例 §

if (duk_has_prop_lstring(ctx, -3, "internal" "\x00" "nul", 12)) {
    printf("obj has 'internal[00]nul'\n");
} else {
    printf("obj does not have 'internal[00]nul'\n");
}

.duk_has_prop_string() 1.0.0 stack property §

原型 §

duk_bool_t duk_has_prop_string(duk_context *ctx, duk_idx_t obj_idx, const char *key);

堆栈 §

[ . . . obj . . . ] [ . . . obj . . . ]

摘要 §

Like duk_has_prop(), but the property name is given as a NUL-terminated C string key.

示例 §

if (duk_has_prop_string(ctx, -3, "myProperty")) {
    printf("obj has 'myProperty'\n");
} else {
    printf("obj does not have 'myProperty'\n");
}

.duk_hex_decode() 1.0.0 codec §

原型 §

void duk_hex_decode(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . hex_val . . . ] [ . . . val . . . ]

摘要 §

Decodes a hex encoded value into a buffer as an in-place operation. If the input is invalid, throws an error.

示例 §

duk_push_string(ctx, "7465737420737472696e67");
duk_hex_decode(ctx, -1);  /* buffer */
printf("hex decoded: %s\n", duk_to_string(ctx, -1));
duk_pop(ctx);

/* Output:
 * hex decoded: test string
 */

请参阅 §


.duk_hex_encode() 1.0.0 codec §

原型 §

const char *duk_hex_encode(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ] [ . . . hex_val . . . ]

摘要 §

Coerces an arbitrary value into a buffer and then encodes the result into hex as an in-place operation. Returns pointer to the resulting string for convenience.

Coercing to a buffer first coerces a non-buffer value into a string, and then coerces the string into a buffer. The resulting buffer contains the string in CESU-8 encoding.

示例 §

duk_push_string(ctx, "foo");
printf("hex encoded: %s\n", duk_hex_encode(ctx, -1));

/* Output:
 * hex encoded: 666f6f
 */

请参阅 §


.duk_insert() 1.0.0 stack §

原型 §

void duk_insert(duk_context *ctx, duk_idx_t to_idx);

堆栈 §

[ . . . old(to_idx) . . . val ] [ . . . val(to_idx) old . . . ]

摘要 §

Insert a value at to_idx with a value popped from the stack top. The previous value at to_idx and any values above it are moved up the stack by a step. If to_idx is an invalid index, throws an error.

Negative indices are evaluated prior to popping the value at the stack top. This is also illustrated by the example.

示例 §

duk_push_int(ctx, 123);
duk_push_int(ctx, 234);
duk_push_int(ctx, 345);       /* -> [ 123 234 345 ] */
duk_push_string(ctx, "foo");  /* -> [ 123 234 345 "foo" ] */
duk_insert(ctx, -3);          /* -> [ 123 "foo" 234 345 ] */

请参阅 §


.duk_inspect_callstack_entry() 2.0.0 stack inspect §

原型 §

void duk_inspect_callstack_entry(duk_context *ctx, duk_int_t level);

堆栈 §

[ . . . ] [ . . . info ]

摘要 §

Inspect callstack entry at level and push an object containing Duktape specific internal information about the entry. The level argument must be negative and mimics the value stack index convention: -1 is the most recent (innermost) call, -2 is its caller, and so on. If the level argument is invalid (e.g. outside of current callstack) undefined is pushed instead.

The result object is not under versioning guarantees so its properties may change even in minor releases (but not patch releases). This is a practical compromise: internals change quite frequently, so the choices are either to make no versioning guarantees or avoid exposing internals at all. As such, calling code should never rely on having a certain set of fields available, and it may be necessary to check DUK_VERSION when interpreting the result fields.

The following table summarizes current properties.

PropertyDescription
function Function being executed. Note that this is a potential sandboxing concern if exposed to untrusted code.
pc Program counter for Ecmascript functions. Zero if executing a native function.
lineNumber Line number for Ecmascript functions. Zero if executing a native function or if pc-to-line translation data is not available.

示例 §

duk_inspect_callstack_entry(ctx, -3);
duk_get_prop_string(ctx, -1, "lineNumber");
printf("immediate caller is executing on line %ld\n", (long) duk_to_int(ctx, -1));
duk_pop_2(ctx);

.duk_inspect_value() 2.0.0 stack inspect §

原型 §

void duk_inspect_value(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ] [ . . . val . . . info ]

摘要 §

Inspect value at idx and push an object containing Duktape specific internal information about the object. If the value stack index is invalid, pushes an object describing a "none" value.

The result object is not under versioning guarantees so its properties may change even in minor releases (but not patch releases). This is a practical compromise: internals change quite frequently, so the choices are either to make no versioning guarantees or avoid exposing internals at all. As such, calling code should never rely on having a certain set of fields available, and it may be necessary to check DUK_VERSION when interpreting the result fields.

The following table summarizes current properties. Memory byte sizes don't include any heap overhead which may vary between 0-16 bytes (or more) depending on the allocation functions being used.

PropertyDescription
type Type number matching DUK_TYPE_xxx from duktape.h.
itag Internal type tag matching internal DUK_TAG_xxx defines. Values may change between versions, and are dependent on config options and the memory layout used for tagged values internally.
hptr Heap pointer for a heap-allocated value. Points to the internal Duktape header structure related to the value type. Same value would be returned from duk_get_heapptr().
refc Reference count. Reference counts are not adjusted in any way, and include references to the value caused by the duk_inspect_value() call.
class For objects, internal class number, matches internal DUK_HOBJECT_CLASS_xxx defines.
hbytes Byte size of main heap object allocation. For some values this is the only allocation, other values have additional allocations.
pbytes Byte size of an object's property table. The property table includes a possible array part, a possible hash part, and a key/value entry part.
bcbytes Byte size of Ecmascript function bytecode (instructions, constants). Shared between all instances (closures) of a certain function template.
dbytes Byte size of the current allocation of a dynamic or external buffer. Note that external buffer allocations are not part of the Duktape heap.
esize Object entry part size in elements.
enext Object entry part first free index (= index of next property slot to be used). In practice matches number of own properties for objects that don't have uncompacted deleted keys.
asize Object array part size in elements, zero if no array part or array part has been abandoned (sparse array). May be larger or smaller than the apparent array .length.
hsize Object hash part size in elements.
tstate Internal thread state, matches internal DUK_HTHREAD_STATE_xxx defines.
variant Identifies type variants for certain types. For strings, variant 0 is an ordinary heap allocated string while variant 1 is an external string. For buffers, variant 0 is a fixed buffer, 1 is a dynamic buffer, and 2 is an external buffer.

示例 §

duk_inspect_value(ctx, -3);
duk_get_prop_string(ctx, -1, "refc");
printf("refcount of value at -3: %ld\n", (long) duk_to_int(ctx, -1));
duk_pop_2(ctx);

.duk_instanceof() 1.3.0 compare §

原型 §

duk_bool_t duk_instanceof(duk_context *ctx, duk_idx_t idx1, duk_idx_t idx2);

堆栈 §

[ . . . val1 . . . val2 . . . ]

摘要 §

Compare values at idx1 and idx2 using the Ecmascript instanceof operator. Returns 1 if val1 instanceof val2, 0 if not. Throws an error if either index is invalid; instanceof itself also throws errors for invalid argument types.

The error throwing behavior for invalid indices differs from the behavior of e.g. duk_equals(), and matches the strictness of instanceof. For example, if rval (idx2) is not a callable object instanceof throws a TypeError. Throwing an error for an invalid index is consistent with instanceof strictness.

示例 §

duk_idx_t idx_val;

duk_get_global_string(ctx, "Error");

if (duk_instanceof(ctx, idx_val, -1)) {
    printf("value at idx_val is an instanceof Error\n");
}

.duk_is_array() 1.0.0 stack §

原型 §

duk_bool_t duk_is_array(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is an object and is an Ecmascript array (has the internal class Array), otherwise returns 0. If idx is invalid, also returns 0.

This function returns 1 when the following Ecmascript expression is true:

Object.prototype.toString.call(val) === '[object Array]'

示例 §

if (duk_is_array(ctx, -3)) {
    /* ... */
}

.duk_is_boolean() 1.0.0 stack §

原型 §

duk_bool_t duk_is_boolean(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a boolean, otherwise returns 0. If idx is invalid, also returns 0.

示例 §

if (duk_is_boolean(ctx, -3)) {
    /* ... */
}

.duk_is_bound_function() 1.0.0 stack function §

原型 §

duk_bool_t duk_is_bound_function(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a Function object which has been created with Ecmascript Function.prototype.bind(), otherwise returns 0. If idx is invalid, also returns 0.

Bound functions are an Ecmascript concept: they point to a target function and supply a this binding and zero or more argument bindings. See Function.prototype.bind (thisArg [, arg1 [, arg2, ...]]).

示例 §

if (duk_is_bound_function(ctx, -3)) {
    /* ... */
}

.duk_is_buffer() 1.0.0 stack buffer §

原型 §

duk_bool_t duk_is_buffer(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a plain buffer, otherwise returns 0. If idx is invalid, also returns 0.

示例 §

if (duk_is_buffer(ctx, -3)) {
    /* ... */
}

.duk_is_buffer_data() 2.0.0 stack buffer §

原型 §

duk_bool_t duk_is_buffer_data(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a plain buffer or any buffer object type, otherwise returns 0. If idx is invalid, also returns 0.

示例 §

if (duk_is_buffer_data(ctx, -3)) {
    /* ... */
}

请参阅 §


.duk_is_c_function() 1.0.0 stack function §

原型 §

duk_bool_t duk_is_c_function(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a Function object and is assocated with a C function, otherwise returns 0. If idx is invalid, also returns 0.

An example of an underlying C function observing the Duktape/C API calling convention:

int my_func(duk_context *ctx) {
    /* ... */
}

示例 §

if (duk_is_c_function(ctx, -3)) {
    /* ... */
}

.duk_is_callable() 1.0.0 stack §

原型 §

duk_bool_t duk_is_callable(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Return 1 if value at idx is callable, otherwise returns 0. Also returns 0 if idx is invalid.

Currently this is the same as duk_is_function().

示例 §

if (duk_is_callable(ctx, -3)) {
    /* ... */
}

.duk_is_constructor_call() 1.0.0 stack §

原型 §

duk_bool_t duk_is_constructor_call(duk_context *ctx);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Return non-zero if current function was called as a constructor (new Foo() instead of Foo()); otherwise returns 0.

This call allows a C function to have different behavior for normal and constructor calls (as is the case for many built-in functions).

示例 §

if (duk_is_constructor_call(ctx)) {
    printf("called as a constructor\n");
} else {
    printf("called as a normal function\n");
}

.duk_is_dynamic_buffer() 1.0.0 stack buffer §

原型 §

duk_bool_t duk_is_dynamic_buffer(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a dynamic buffer, otherwise returns 0. If idx is invalid, also returns 0.

示例 §

if (duk_is_dynamic_buffer(ctx, -3)) {
    /* ... */
}

.duk_is_ecmascript_function() 1.0.0 stack function §

原型 §

duk_bool_t duk_is_ecmascript_function(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a Function object which has been compiled from Ecmascript source code, otherwise returns 0. If idx is invalid, also returns 0.

Internally Ecmascript functions are compiled into bytecode and executed with the Ecmascript bytecode interpreter.

示例 §

if (duk_is_ecmascript_function(ctx, -3)) {
    /* ... */
}

.duk_is_error() 1.1.0 stack error §

原型 §

duk_bool_t duk_is_error(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx inherits from Error, otherwise returns 0. If idx is invalid, also returns 0.

示例 §

if (duk_is_error(ctx, -3)) {
    /* Inherits from Error, attempt to print stack trace */
    duk_get_prop_string(ctx, -3, "stack");
    printf("%s\n", duk_safe_to_string(ctx, -1));
    duk_pop(ctx);
}

.duk_is_eval_error() 1.4.0 stack error §

原型 §

duk_bool_t duk_is_eval_error(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx inherits from EvalError, otherwise returns 0. If idx is invalid, also returns 0. This is a convenience call for using duk_get_error_code() == DUK_ERR_EVAL_ERROR.

示例 §

if (duk_is_eval_error(ctx, -3)) {
    /* ... */
}

.duk_is_fixed_buffer() 1.0.0 stack buffer §

原型 §

duk_bool_t duk_is_fixed_buffer(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a fixed buffer, otherwise returns 0. If idx is invalid, also returns 0.

示例 §

if (duk_is_fixed_buffer(ctx, -3)) {
    /* ... */
}

.duk_is_function() 1.0.0 stack function §

原型 §

duk_bool_t duk_is_function(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is an object and is a function (has the internal class Function), otherwise returns 0. If idx is invalid, also returns 0.

This function returns 1 when the following Ecmascript expression is true:

Object.prototype.toString.call(val) === '[object Function]'

To determine the specific type of the function, use:

示例 §

if (duk_is_function(ctx, -3)) {
    /* ... */
}

.duk_is_lightfunc() stack §

原型 §

duk_bool_t duk_is_lightfunc(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a lightfunc, otherwise returns 0. If idx is invalid, also returns 0.

示例 §

if (duk_is_lightfunc(ctx, -3)) {
    /* ... */
}

.duk_is_nan() 1.0.0 stack §

原型 §

duk_bool_t duk_is_nan(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a NaN (a special number value), otherwise returns 0. If idx is invalid, also returns 0.

IEEE has a large number of different NaN values. Duktape normalizes NaN values internally. This function returns 1 for any kind of a NaN.

示例 §

if (duk_is_nan(ctx, -3)) {
    /* ... */
}

.duk_is_null() 1.0.0 stack §

原型 §

duk_bool_t duk_is_null(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is either null, otherwise returns 0. If idx is invalid, also returns 0.

示例 §

if (duk_is_null(ctx, -3)) {
    /* ... */
}

.duk_is_null_or_undefined() 1.0.0 stack §

原型 §

duk_bool_t duk_is_null_or_undefined(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is either null or undefined, otherwise returns 0. If idx is invalid, also returns 0.

This API call is similar to a (x == null) comparison in Ecmascript, which is true for both null and undefined.

示例 §

if (duk_is_null_or_undefined(ctx, -3)) {
    /* ... */
}

.duk_is_number() 1.0.0 stack §

原型 §

duk_bool_t duk_is_number(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a number, otherwise returns 0. If idx is invalid, also returns 0.

示例 §

if (duk_is_number(ctx, -3)) {
    /* ... */
}

.duk_is_object() 1.0.0 stack object §

原型 §

duk_bool_t duk_is_object(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is an object, otherwise returns 0. If idx is invalid, also returns 0.

Note that many values are considered to be an object, e.g.:

  • Ecmascript object
  • Ecmascript array
  • Ecmascript function
  • Duktape thread (coroutine)
  • Duktape internal objects

Specific object types can be checked with separate API calls, e.g. duk_is_array().

示例 §

if (duk_is_object(ctx, -3)) {
    /* ... */
}

.duk_is_object_coercible() 1.0.0 stack object §

原型 §

duk_bool_t duk_is_object_coercible(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is object coercible, as defined in CheckObjectCoercible, otherwise returns 0. If idx is invalid, also returns 0.

All Ecmascript types are object coercible except undefined and null. The custom buffer and pointer types are object coercible.

示例 §

if (duk_is_object_coercible(ctx, -3)) {
    /* ... */
}

.duk_is_pointer() 1.0.0 stack §

原型 §

duk_bool_t duk_is_pointer(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a pointer, otherwise returns 0. If idx is invalid, also returns 0.

示例 §

if (duk_is_pointer(ctx, -3)) {
    /* ... */
}

.duk_is_primitive() 1.0.0 stack §

原型 §

duk_bool_t duk_is_primitive(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a primitive type, as defined in ToPrimitive, otherwise returns 0. If idx is invalid, also returns 0.

Any standard type other than an object is a primitive type. The custom plain pointer type is also considered a primitive type. However, the custom plain buffer type (which behaves like an Uint8Array object in most situations) and lightfunc type (which behaves like a Function object in most situations) are not considered a primitive type. This matches the behavior of duk_to_primitive() which (usually) coerces e.g. a plain buffer to the string [object Uint8Array].

示例 §

if (duk_is_primitive(ctx, -3)) {
    /* ... */
}

.duk_is_range_error() 1.4.0 stack error §

原型 §

duk_bool_t duk_is_range_error(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx inherits from RangeError, otherwise returns 0. If idx is invalid, also returns 0. This is a convenience call for using duk_get_error_code() == DUK_ERR_RANGE_ERROR.

示例 §

if (duk_is_range_error(ctx, -3)) {
    /* ... */
}

.duk_is_reference_error() 1.4.0 stack error §

原型 §

duk_bool_t duk_is_reference_error(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx inherits from ReferenceError, otherwise returns 0. If idx is invalid, also returns 0. This is a convenience call for using duk_get_error_code() == DUK_ERR_REFERENCE_ERROR.

示例 §

if (duk_is_reference_error(ctx, -3)) {
    /* ... */
}

.duk_is_strict_call() 1.0.0 function §

原型 §

duk_bool_t duk_is_strict_call(duk_context *ctx);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Check whether the current (Duktape/C) function call is strict or not. Returns 1 if the current function call is strict, 0 otherwise. As of Duktape 0.12.0, this function always returns 1 when called from user code (even if the call stack is empty).

示例 §

if (duk_is_strict_call(ctx)) {
    printf("strict call\n");
} else {
    printf("non-strict call\n");
}

.duk_is_string() 1.0.0 string stack §

原型 §

duk_bool_t duk_is_string(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a string, otherwise returns 0. If idx is invalid, also returns 0.

Symbol values are visible in the C API as strings so that both duk_is_symbol() and duk_is_string() are true. This behavior is similar to Duktape 1.x internal strings. Symbols are still an experimental feature; for now, you can distinguish Symbols from ordinary strings using duk_is_symbol(). For the internal representation, see symbols.rst.

示例 §

if (duk_is_string(ctx, -3)) {
    /* ... */
}

.duk_is_symbol() 2.0.0 symbol string stack §

原型 §

duk_bool_t duk_is_symbol(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is a symbol, otherwise returns 0. If idx is invalid, also returns 0.

Symbol values are visible in the C API as strings so that both duk_is_symbol() and duk_is_string() are true. This behavior is similar to Duktape 1.x internal strings. Symbols are still an experimental feature; for now, you can distinguish Symbols from ordinary strings using duk_is_symbol(). For the internal representation, see symbols.rst.

示例 §

if (duk_is_symbol(ctx, -3)) {
    /* ... */
}

.duk_is_syntax_error() 1.4.0 stack error §

原型 §

duk_bool_t duk_is_syntax_error(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx inherits from SyntaxError, otherwise returns 0. If idx is invalid, also returns 0. This is a convenience call for using duk_get_error_code() == DUK_ERR_SYNTAX_ERROR.

示例 §

if (duk_is_syntax_error(ctx, -3)) {
    /* ... */
}

.duk_is_thread() 1.0.0 thread stack §

原型 §

duk_bool_t duk_is_thread(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is an object and is a Duktape thread (coroutine), otherwise returns 0. If idx is invalid, also returns 0.

示例 §

if (duk_is_thread(ctx, -3)) {
    /* ... */
}

.duk_is_type_error() 1.4.0 stack error §

原型 §

duk_bool_t duk_is_type_error(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx inherits from TypeError, otherwise returns 0. If idx is invalid, also returns 0. This is a convenience call for using duk_get_error_code() == DUK_ERR_TYPE_ERROR.

示例 §

if (duk_is_type_error(ctx, -3)) {
    /* ... */
}

.duk_is_undefined() 1.0.0 stack §

原型 §

duk_bool_t duk_is_undefined(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx is either undefined, otherwise returns 0. If idx is invalid, also returns 0.

示例 §

if (duk_is_undefined(ctx, -3)) {
    /* ... */
}

.duk_is_uri_error() 1.4.0 stack error §

原型 §

duk_bool_t duk_is_uri_error(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Returns 1 if value at idx inherits from URIError, otherwise returns 0. If idx is invalid, also returns 0. This is a convenience call for using duk_get_error_code() == DUK_ERR_URI_ERROR.

示例 §

if (duk_is_uri_error(ctx, -3)) {
    /* ... */
}

.duk_is_valid_index() 1.0.0 stack §

原型 §

duk_bool_t duk_is_valid_index(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Validate argument index, return 1 if index is valid, 0 otherwise.

示例 §

if (duk_is_valid_index(ctx, -3)) {
    printf("index -3 is valid\n");
} else {
    printf("index -3 is not valid\n");
}

.duk_join() 1.0.0 string §

原型 §

void duk_join(duk_context *ctx, duk_idx_t count);

堆栈 §

[ . . . sep val1 . . . valN ] [ . . . result ]

摘要 §

Join zero or more values into a result string with a separator between each value. The separator and the input values are automatically coerced with ToString().

This primitive minimizes the number of intermediate string interning operations and is better than joining strings manually.

示例 §

duk_push_string(ctx, "; ");
duk_push_string(ctx, "foo");
duk_push_int(ctx, 123);
duk_push_true(ctx);
duk_join(ctx, 3);

printf("result: %s\n", duk_get_string(ctx, -1));  /* "foo; 123; true" */
duk_pop(ctx);

请参阅 §


.duk_json_decode() 1.0.0 json codec §

原型 §

void duk_json_decode(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . json_val . . . ] [ . . . val . . . ]

摘要 §

Decodes an arbitrary JSON value as an in-place operation. If the input is invalid, throws an error.

示例 §

duk_push_string(ctx, "{\"meaningOfLife\":42}");
duk_json_decode(ctx, -1);
duk_get_prop_string(ctx, -1, "meaningOfLife");
printf("JSON decoded meaningOfLife is: %s\n", duk_to_string(ctx, -1));
duk_pop_2(ctx);

/* Output:
 * JSON decoded meaningOfLife is: 42
 */

请参阅 §


.duk_json_encode() 1.0.0 json codec §

原型 §

const char *duk_json_encode(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ] [ . . . json_val . . . ]

摘要 §

Encodes an arbitrary value into its JSON representation as an in-place operation. Returns pointer to the resulting string for convenience.

示例 §

duk_push_object(ctx);
duk_push_int(ctx, 42);
duk_put_prop_string(ctx, -2, "meaningOfLife");
printf("JSON encoded: %s\n", duk_json_encode(ctx, -1));
duk_pop(ctx);

/* Output:
 * JSON encoded: {"meaningOfLife":42}
 */

请参阅 §


.duk_load_function() 1.3.0 stack bytecode §

原型 §

void duk_load_function(duk_context *ctx);

堆栈 §

[ . . . bytecode ] [ . . . function ]

摘要 §

Load a buffer containing bytecode, recreating the original Ecmascript function (with some limitations). You must ensure that the bytecode has been dumped with a compatible Duktape version and that the bytecode has not been modified since. Loading bytecode from an untrusted source is memory unsafe and may load to exploitable vulnerabilities.

For more information on Duktape bytecode dump/load, supported features, and known limitations, see bytecode.rst. Duktape bytecode format is not intended for obfuscation, see notes on Obfuscation.

示例 §

duk_eval_string(ctx, "(function helloWorld() { print('hello world'); })");
duk_dump_function(ctx);
/* stack top now contains a buffer containing helloWorld bytecode */

duk_load_function(ctx);  /* [ ... bytecode ] -> [ ... function ] */
duk_call(ctx, 0);
duk_pop(ctx);

请参阅 §


.duk_map_string() 1.0.0 string §

原型 §

void duk_map_string(duk_context *ctx, duk_idx_t idx, duk_map_char_function callback, void *udata);

堆栈 §

[ . . . val . . . ] [ . . . val . . . ]

摘要 §

Process string at idx, calling callback for each codepoint of the string. The callback is given the udata argument and a codepoint and returns a replacement codepoint. If successful, a new string consisting of the replacement codepoints replaces the original. If the value is not a string or the index is invalid, throws an error.

示例 §

static duk_codepoint_t map_char(void *udata, duk_codepoint_t codepoint) {
    /* Convert ASCII to uppercase. */
    if (codepoint >= (duk_codepoint_t) 'a' && codepoint <= (duk_codepoint_t) 'z') {
        return codepoint - (duk_codepoint_t) 'a' + (duk_codepoint_t) 'A';
    }
    return codepoint;
}

duk_push_string(ctx, "test_string");
duk_map_string(ctx, -1, map_char, NULL);
printf("result: %s\n", duk_to_string(ctx, -1));
duk_pop(ctx);

请参阅 §


.duk_new() 1.0.0 object call §

原型 §

void duk_new(duk_context *ctx, duk_idx_t nargs);

堆栈 §

[ . . . constructor arg1 . . . argN ] [ . . . retval ]

摘要 §

Call a constructor function with nargs arguments (not counting the function itself). The function and its arguments are replaced by a single return value. An error thrown during the constructor call is not automatically caught.

The target function this binding is set to a freshly created empty object. If constructor.prototype is an object, the internal prototype of the new object is set to that value; otherwise the standard built-in Object prototype is used as the internal prototype. The return value of the target function determines what the result of the constructor call is. If the constructor returns an object, it replaces the fresh empty object; otherwise the fresh empty object (possibly modified by the constructor) is returned. See [[Construct]].

示例 §

/* Assume target function is already on stack at func_idx.
 * Equivalent to Ecmascript 'new func("foo", 123)'.
 */
duk_idx_t func_idx = /* ... */;

duk_dup(ctx, func_idx);
duk_push_string(ctx, "foo");
duk_push_int(ctx, 123);
duk_new(ctx, 2);  /* [ ... func "foo" 123 ] -> [ ... res ] */
printf("result is object: %d\n", (int) duk_is_object(ctx, -1));
duk_pop(ctx);

请参阅 §


.duk_next() 1.0.0 property object §

原型 §

duk_bool_t duk_next(duk_context *ctx, duk_idx_t enum_idx, duk_bool_t get_value);

堆栈 §

[ . . . enum . . . ] [ . . . enum . . . ] (if enum empty; function returns zero)
[ . . . enum . . . ] [ . . . enum . . . key ] (if enum not empty and get_value == 0; function returns non-zero)
[ . . . enum . . . ] [ . . . enum . . . key value ] (if enum not empty and get_value != 0; function returns non-zero)

摘要 §

Get the next key (and optionally value) from an enumerator created with duk_enum(). If the enumeration has been exhausted, nothing is pushed to the stack and the function returns zero. Otherwise the key is pushed to the stack, followed by the value if get_value is non-zero, and the function returns non-zero.

Note that getting the value may invoke a getter which may have arbitrary side effects (and may throw an error).

示例 §

while (duk_next(ctx, enum_idx, 1)) {
    printf("key=%s, value=%s\n", duk_to_string(ctx, -2), duk_to_string(ctx, -1));
    duk_pop_2(ctx);
}

请参阅 §


.duk_normalize_index() 1.0.0 stack §

原型 §

duk_idx_t duk_normalize_index(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Normalize argument index relative to the bottom of the current frame. The resulting index will be 0 or greater and will be independent of later stack modifications. If the input index is invalid, returns DUK_INVALID_INDEX. If you prefer that an error be thrown for an invalid index, use duk_require_normalize_index().

示例 §

duk_idx_t idx = duk_normalize_index(ctx, -3);

.duk_pcall() 1.0.0 protected call §

原型 §

duk_int_t duk_pcall(duk_context *ctx, duk_idx_t nargs);

堆栈 §

[ . . . func arg1 . . . argN ] [ . . . retval ] (if success, return value == 0)
[ . . . func arg1 . . . argN ] [ . . . err ] (if failure, return value != 0)

摘要 §

Call target function func with nargs arguments (not counting the function itself). The function and its arguments are replaced by a single return value or a single error value. An error thrown during the function call is caught.

The return value is:

  • DUK_EXEC_SUCCESS (0): call succeeded, nargs arguments are replaced with a single return value. (This return code constant is guaranteed to be zero, so that one can check for success with a "zero or non-zero" check.)
  • DUK_EXEC_ERROR: call failed, nargs arguments are replaced with a single error value. (In exceptional cases, e.g. when there are too few arguments on the value stack, the call returns non-zero but may leave the stack in an inconsistent state.)
Unlike most Duktape API calls, this call returns zero on success. This allows multiple error codes to be defined later.

Error objects caught are typically instances of Error and have useful properties like .stack, .fileName, and .lineNumber. These can be accessed using the normal property methods. However, arbitrary values can be thrown so you should avoid assuming that's always the case.

The target function this binding is initially set to undefined. If the target function is not strict, the binding is replaced by the global object before the function is invoked; see Entering Function Code. If you want to control the this binding, you can use duk_pcall_method() or duk_pcall_prop() instead.

示例 §

/* Assume target function is already on stack at func_idx; the target
 * function adds arguments and returns the result.
 */

duk_idx_t func_idx;
duk_int_t rc;

/* Basic example: function call and duk_safe_to_string() error print. */

duk_dup(ctx, func_idx);
duk_push_int(ctx, 2);
duk_push_int(ctx, 3);
rc = duk_pcall(ctx, 2);  /* [ ... func 2 3 ] -> [ 5 ] */
if (rc == DUK_EXEC_SUCCESS) {
    printf("2+3=%ld\n", (long) duk_get_int(ctx, -1));
} else {
    /* Coercing with duk_safe_to_string() is a useful default, but you can
     * also look up e.g. the .stack property of the error.
     */
    printf("error: %s\n", duk_safe_to_string(ctx, -1));
}
duk_pop(ctx);

/* Accessing .stack to print a stack trace if the value caught is an
 * Error instance.
 */

duk_dup(ctx, func_idx);
duk_push_int(ctx, 2);
duk_push_int(ctx, 3);
rc = duk_pcall(ctx, 2);  /* [ ... func 2 3 ] -> [ 5 ] */
if (rc == DUK_EXEC_SUCCESS) {
    printf("2+3=%ld\n", (long) duk_get_int(ctx, -1));
} else {
    if (duk_is_error(ctx, -1)) {
        /* Accessing .stack might cause an error to be thrown, so wrap this
         * access in a duk_safe_call() if it matters.
         */
        duk_get_prop_string(ctx, -1, "stack");
        printf("error: %s\n", duk_safe_to_string(ctx, -1));
        duk_pop(ctx);
    } else {
        /* Non-Error value, coerce safely to string. */
        printf("error: %s\n", duk_safe_to_string(ctx, -1));
    }
}
duk_pop(ctx);

.duk_pcall_method() 1.0.0 protected call §

原型 §

duk_int_t duk_pcall_method(duk_context *ctx, duk_idx_t nargs);

堆栈 §

[ . . . func this arg . . . argN ] [ . . . retval ] (if success, return value == 0)
[ . . . func this arg . . . argN ] [ . . . err ] (if failure, return value != 0)

摘要 §

Like duk_pcall(), but the target function func is called with an explicit this binding given on the value stack.

示例 §

/* The target function here prints:
 *
 *    this: 123
 *    2 3
 *
 * and returns 5.
 */

duk_int_t rc;

duk_push_string(ctx, "function(x,y) { print('this:', this); "
                     "print(x,y); return x+y; }");
duk_eval(ctx);  /* -> [ ... func ] */
duk_push_int(ctx, 123);
duk_push_int(ctx, 2);
duk_push_int(ctx, 3);
rc = duk_pcall_method(ctx, 2);  /* [ ... func 123 2 3 ] -> [ 5 ] */
if (rc == DUK_EXEC_SUCCESS) {
    printf("2+3=%ld\n", (long) duk_get_int(ctx, -1));  /* prints 5 */
} else {
    printf("error: %s\n", duk_to_string(ctx, -1));
}
duk_pop(ctx);

.duk_pcall_prop() 1.0.0 protected property call §

原型 §

duk_int_t duk_pcall_prop(duk_context *ctx, duk_idx_t obj_idx, duk_idx_t nargs);

堆栈 §

[ . . . obj . . . key arg1 . . . argN ] [ . . . obj . . . retval ] (if success, return value == 0)
[ . . . obj . . . key arg1 . . . argN ] [ . . . obj . . . err ] (if failure, return value != 0)

摘要 §

Like duk_pcall(), but the target function is looked up from obj.key and obj is used as the function's this binding.

示例 §

/* obj.myAdderMethod(2,3) -> 5 */
duk_idx_t obj_idx;
duk_int_t rc;

duk_push_string(ctx, "myAdderMethod");
duk_push_int(ctx, 2);
duk_push_int(ctx, 3);
rc = duk_pcall_prop(ctx, obj_idx, 2);  /* [ ... "myAdderMethod" 2 3 ] -> [ ... 5 ] */
if (rc == DUK_EXEC_SUCCESS) {
    printf("2+3=%ld\n", (long) duk_get_int(ctx, -1));
} else {
    printf("error: %s\n", duk_to_string(ctx, -1));
}
duk_pop(ctx);

.duk_pcompile() 1.0.0 protected compile §

原型 §

duk_int_t duk_pcompile(duk_context *ctx, duk_uint_t flags);

堆栈 §

[ . . . source filename ] [ . . . function ] (if success, return value == 0)
[ . . . source filename ] [ . . . err ] (if failure, return value != 0)

摘要 §

Like duk_compile() but catches errors related to compilation (such as syntax errors in the source). A zero return value indicates success and the compiled function is left on the stack top. A non-zero return value indicates an error, and the error is left on the stack top.

示例 §

duk_push_string(ctx, "print('program'); syntax error here=");
duk_push_string(ctx, "hello-with-syntax-error");
if (duk_pcompile(ctx, 0) != 0) {
    printf("compile failed: %s\n", duk_safe_to_string(ctx, -1));
} else {
    duk_call(ctx, 0);      /* [ func ] -> [ result ] */
    printf("program result: %s\n", duk_safe_to_string(ctx, -1));
}
duk_pop(ctx);

.duk_pcompile_lstring() 1.0.0 protected compile §

原型 §

duk_int_t duk_pcompile_lstring(duk_context *ctx, duk_uint_t flags, const char *src, duk_size_t len);

堆栈 §

[ . . . ] [ . . . function ] (if success, return value == 0)
[ . . . ] [ . . . err ] (if failure, return value != 0)

摘要 §

Like duk_pcompile(), but the compile input is given as a C string with explicit length. The filename associated with the function is "input".

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

const char *src = /* ... */;
duk_size_t len = /* ... */;

if (duk_pcompile_lstring(ctx, 0, src, len) != 0) {
    printf("compile failed: %s\n", duk_safe_to_string(ctx, -1));
} else {
    duk_call(ctx, 0);      /* [ func ] -> [ result ] */
    printf("program result: %s\n", duk_safe_to_string(ctx, -1));
}
duk_pop(ctx);

.duk_pcompile_lstring_filename() 1.0.0 protected compile §

原型 §

duk_int_t duk_pcompile_lstring_filename(duk_context *ctx, duk_uint_t flags, const char *src, duk_size_t len);

堆栈 §

[ . . . filename ] [ . . . function ] (if success, return value == 0)
[ . . . filename ] [ . . . err ] (if failure, return value != 0)

摘要 §

Like duk_pcompile(), but the compile input is given as a C string with explicit length.

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

const char *src = /* ... */;
duk_size_t len = /* ... */;

duk_push_string(ctx, "myFile.js");
if (duk_pcompile_lstring_filename(ctx, 0, src, len) != 0) {
    printf("compile failed: %s\n", duk_safe_to_string(ctx, -1));
} else {
    duk_call(ctx, 0);      /* [ func ] -> [ result ] */
    printf("program result: %s\n", duk_safe_to_string(ctx, -1));
}
duk_pop(ctx);

.duk_pcompile_string() 1.0.0 protected compile §

原型 §

duk_int_t duk_pcompile_string(duk_context *ctx, duk_uint_t flags, const char *src);

堆栈 §

[ . . . ] [ . . . function ] (if success, return value == 0)
[ . . . ] [ . . . err ] (if failure, return value != 0)

摘要 §

Like duk_pcompile(), but the compile input is given as a C string. The filename associated with the function is "input".

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

if (duk_pcompile_string(ctx, 0, "print('program code'); syntax error here=") != 0) {
    printf("compile failed: %s\n", duk_safe_to_string(ctx, -1));
} else {
    duk_call(ctx, 0);      /* [ func ] -> [ result ] */
    printf("program result: %s\n", duk_safe_to_string(ctx, -1));
}
duk_pop(ctx);

.duk_pcompile_string_filename() 1.0.0 protected compile §

原型 §

duk_int_t duk_pcompile_string_filename(duk_context *ctx, duk_uint_t flags, const char *src);

堆栈 §

[ . . . filename ] [ . . . function ] (if success, return value == 0)
[ . . . filename ] [ . . . err ] (if failure, return value != 0)

摘要 §

Like duk_pcompile(), but the compile input is given as a C string.

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

duk_push_string(ctx, "myFile.js");
if (duk_pcompile_string_filename(ctx, 0, "print('program code'); syntax error here=") != 0) {
    printf("compile failed: %s\n", duk_safe_to_string(ctx, -1));
} else {
    duk_call(ctx, 0);      /* [ func ] -> [ result ] */
    printf("program result: %s\n", duk_safe_to_string(ctx, -1));
}
duk_pop(ctx);

.duk_peval() 1.0.0 protected compile §

原型 §

duk_int_t duk_peval(duk_context *ctx);

堆栈 §

[ . . . source ] [ . . . result ] (if success, return value == 0)
[ . . . source ] [ . . . err ] (if failure, return value != 0)

摘要 §

Like duk_eval() but catches errors related to compilation (such as syntax errors in the source). A zero return value indicates success and the eval result is left on the stack top. A non-zero return value indicates an error, and the error is left on the stack top.

示例 §

duk_push_string(ctx, "print('Hello world!'); syntax error here=");
if (duk_peval(ctx) != 0) {
    printf("eval failed: %s\n", duk_safe_to_string(ctx, -1));
} else {
    printf("result is: %s\n", duk_safe_to_string(ctx, -1));
}
duk_pop(ctx);

.duk_peval_lstring() 1.0.0 protected compile §

原型 §

duk_int_t duk_peval_lstring(duk_context *ctx, const char *src, duk_size_t len);

堆栈 §

[ . . . ] [ . . . result ] (if success, return value == 0)
[ . . . ] [ . . . err ] (if failure, return value != 0)

摘要 §

Like duk_peval(), but the eval input is given as a C string with explicit length. The filename associated with the temporary eval function is "eval".

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

const char *src = /* ... */;
duk_size_t len = /* ... */;

if (duk_peval_lstring(ctx, src, len) != 0) {
    printf("eval failed: %s\n", duk_safe_to_string(ctx, -1));
} else {
    printf("result is: %s\n", duk_get_string(ctx, -1));
}
duk_pop(ctx);

.duk_peval_lstring_noresult() 1.0.0 protected compile §

原型 §

duk_int_t duk_peval_lstring_noresult(duk_context *ctx, const char *src, duk_size_t len);

堆栈 §

[ . . . ] [ . . . ]

摘要 §

Like duk_peval_lstring(), but leaves no result on the value stack (regardless of success/error result).

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

const char *src = /* ... */;
duk_size_t len = /* ... */;

if (duk_peval_lstring_noresult(ctx, src, len) != 0) {
    printf("eval failed\n");
} else {
    printf("eval successful\n");
}

.duk_peval_noresult() 1.0.0 protected compile §

原型 §

duk_int_t duk_peval_noresult(duk_context *ctx);

堆栈 §

[ . . . source ] [ . . . ]

摘要 §

Like duk_peval() but leaves no result on the value stack (regardless of success/error result).

示例 §

duk_push_string(ctx, "print('Hello world!'); syntax error here=");
if (duk_peval_noresult(ctx) != 0) {
    printf("eval failed\n");
} else {
    printf("eval successful\n");
}

.duk_peval_string() 1.0.0 protected compile §

原型 §

duk_int_t duk_peval_string(duk_context *ctx, const char *src);

堆栈 §

[ . . . ] [ . . . result ] (if success, return value == 0)
[ . . . ] [ . . . err ] (if failure, return value != 0)

摘要 §

Like duk_peval(), but the eval input is given as a C string. The filename associated with the temporary eval function is "eval".

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

if (duk_peval_string(ctx, "'testString'.toUpperCase()") != 0) {
    printf("eval failed: %s\n", duk_safe_to_string(ctx, -1));
} else {
    printf("result is: %s\n", duk_get_string(ctx, -1));
}
duk_pop(ctx);

.duk_peval_string_noresult() 1.0.0 protected compile §

原型 §

duk_int_t duk_peval_string_noresult(duk_context *ctx, const char *src);

堆栈 §

[ . . . ] [ . . . ]

摘要 §

Like duk_peval_string(), but leaves no result on the value stack (regardless of success/error result).

With this variant, the input source code is not interned by Duktape which is useful in low memory environments.

示例 §

if (duk_peval_string_noresult(ctx, "print('testString'.toUpperCase());") != 0) {
    printf("eval failed\n");
} else {
    printf("eval successful\n");
}

.duk_pnew() 1.3.0 protected object call §

原型 §

duk_ret_t duk_pnew(duk_context *ctx, duk_idx_t nargs);

堆栈 §

[ . . . constructor arg1 . . . argN ] [ . . . retval ] (if success, return value == 0)
[ . . . constructor arg1 . . . argN ] [ . . . err ] (if failure, return value != 0)

摘要 §

Like duk_new() but catches errors. A zero return value indicates success and the constructor result is left on the stack top. A non-zero return value indicates an error, and the error is left on the stack top.

示例 §

duk_ret_t rc;

/* Protected call to: new MyConstructor("foo", 123) */
duk_eval_string(ctx, "MyConstructor");
duk_push_string(ctx, "foo");
duk_push_int(ctx, 123);
rc = duk_pnew(ctx, 2);  /* [ ... func "foo" 123 ] -> [ ... res ] */
if (rc != 0) {
    printf("failed: %s\n", duk_safe_to_string(ctx, -1));
} else {
    printf("success\n");
}
duk_pop(ctx);

请参阅 §


.duk_pop() 1.0.0 stack §

原型 §

void duk_pop(duk_context *ctx);

堆栈 §

[ . . . val ] [ . . . ]

摘要 §

Pop one element off the stack. If the stack is empty, throws an error.

To pop multiple elements, use duk_pop_n() or the shortcuts for common cases: duk_pop_2() and duk_pop_3().

示例 §

duk_pop(ctx);

.duk_pop_2() 1.0.0 stack §

原型 §

void duk_pop_2(duk_context *ctx);

堆栈 §

[ . . . val1 val2 ] [ . . . ]

摘要 §

Pop two elements off the stack. If the stack has fewer than two elements, throws an error.

示例 §

duk_pop_2(ctx);

.duk_pop_3() 1.0.0 stack §

原型 §

void duk_pop_3(duk_context *ctx);

堆栈 §

[ . . . val1 val2 val3 ] [ . . . ]

摘要 §

Pop three elements off the stack. If the stack has fewer than three elements, throws an error.

示例 §

duk_pop_3(ctx);

.duk_pop_n() 1.0.0 stack §

原型 §

void duk_pop_n(duk_context *ctx, duk_idx_t count);

堆栈 §

[ . . . val1 . . . valN ] [ . . . ]

摘要 §

Pop count elements off the stack. If the stack has fewer than count elements, throws an error. If count is zero, the call is a no-op. Negative counts cause an error to be thrown.

示例 §

duk_pop_n(ctx, 10);

.duk_push_array() 1.0.0 stack object §

原型 §

duk_idx_t duk_push_array(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . arr ]

摘要 §

Push an empty array to the stack. Returns non-negative index (relative to stack bottom) of the pushed array.

示例 §

duk_idx_t arr_idx;

arr_idx = duk_push_array(ctx);
duk_push_string(ctx, "foo");
duk_put_prop_index(ctx, arr_idx, 0);
duk_push_string(ctx, "bar");
duk_put_prop_index(ctx, arr_idx, 1);

/* array is now: [ "foo", "bar" ], and array.length is 2 (automatically
 * updated for Ecmascript arrays).
 */

duk_pop(ctx);  /* pop array */

.duk_push_bare_object() 2.0.0 stack object §

原型 §

duk_idx_t duk_push_bare_object(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . obj ]

摘要 §

Similar to duk_push_object() but the pushed object doesn't inherit from any other object, i.e. its internal prototype is null. This call is equivalent to Object.create(null). Returns non-negative index (relative to stack bottom) of the pushed object.

示例 §

duk_idx_t obj_idx;

obj_idx = duk_push_bare_object(ctx);

请参阅 §


.duk_push_boolean() 1.0.0 stack §

原型 §

void duk_push_boolean(duk_context *ctx, duk_bool_t val);

堆栈 §

[ . . . ] [ . . . true ] (if val != 0)
[ . . . ] [ . . . false ] (if val == 0)

摘要 §

Push true (if val != 0) or false (if val == 0) to the stack.

示例 §

duk_push_boolean(ctx, 0);  /* -> [ ... false ] */
duk_push_boolean(ctx, 1);  /* -> [ ... false true ] */
duk_push_boolean(ctx, -3);  /* -> [ ... false true true ] */

.duk_push_buffer() 1.0.0 stack buffer §

原型 §

void *duk_push_buffer(duk_context *ctx, duk_size_t size, duk_bool_t dynamic);

堆栈 §

[ . . . ] [ . . . buf ]

摘要 §

Allocate a new buffer of size bytes and push it to the value stack. Returns a non-NULL pointer to the buffer data area; for a zero-size buffer, may return either NULL or non-NULL. The buffer data area is automatically zeroed. If dynamic is non-zero, the buffer will be resizable, otherwise the buffer will have a fixed size. Throws an error if allocation fails.

There are also shortcut variants duk_push_fixed_buffer() and duk_push_dynamic_buffer().

A dynamic buffer requires two memory allocations internally: one for the buffer header and another for the currently allocated data area. A fixed buffer only requires a single allocation: the data area follows the buffer header.
Be careful when requesting a zero length dynamic buffer: a NULL data pointer is not an error and should not confuse calling code.
Duktape can be compiled with a feature option which disables automatic zeroing of allocated buffer data. If this is the case, you need to zero the buffer manually if necessary.

示例 §

/* Allocate a fixed buffer of 1024 bytes.  There is no need to check for
 * the return value: an error is thrown if allocation fails.
 */

void *p;

p = duk_push_buffer(ctx, 1024, 0);
printf("allocated buffer, data area: %p\n", p);

.duk_push_buffer_object() 1.3.0 stack bufferobject §

原型 §

void duk_push_buffer_object(duk_context *ctx, duk_idx_t idx_buffer, duk_size_t byte_offset, duk_size_t byte_length, duk_uint_t flags);

堆栈 §

[ . . . buffer . . . ] [ . . . buffer . . . bufobj ]

摘要 §

Push a new buffer object or a buffer view object. An underlying plain buffer is provided at index idx_buffer. The type of the buffer or view is given in flags (e.g. DUK_BUFOBJ_UINT16ARRAY). The active range or "slice" used from the underlying buffer is indicated by byte_offset and byte_length.

The available buffer types are:

DefineBuffer/view type
DUK_BUFOBJ_NODEJS_BUFFERBuffer (Node.js), a Uint8Array inheriting from Buffer.prototype
DUK_BUFOBJ_ARRAYBUFFERArrayBuffer
DUK_BUFOBJ_DATAVIEWDataView
DUK_BUFOBJ_INT8ARRAYInt8Array
DUK_BUFOBJ_UINT8ARRAYUint8Array
DUK_BUFOBJ_UINT8CLAMPEDARRAYUint8ClampedArray
DUK_BUFOBJ_INT16ARRAYInt16Array
DUK_BUFOBJ_UINT16ARRAYUint16Array
DUK_BUFOBJ_INT32ARRAYInt32Array
DUK_BUFOBJ_UINT32ARRAYUint32Array
DUK_BUFOBJ_FLOAT32ARRAYFloat32Array
DUK_BUFOBJ_FLOAT64ARRAYFloat64Array

When anything other than an ArrayBuffer is pushed, an ArrayBuffer backing the view is automatically created. It is accessible through the buffer property of the view object. The ArrayBuffer's internal byteOffset will be zero so that the ArrayBuffer's index byteOffset matches the view's index 0. The ArrayBuffer's byteLength will be byteLength will be byte_offset + byte_length so that the view range is valid for the ArrayBuffer.

The underlying plain buffer should normally cover the range indicated by the byte_offset and byte_length arguments, but memory safety is guaranteed even if that is not the case. For example, an attempt to read values outside the underlying buffer will return zero. The underlying buffer size is intentionally not checked when creating a buffer object: even if the buffer fully covered the byte range during creation, it might be resized later.

示例 §

/* Map byte range [100,150[ of plain buffer at idx_plain_buf into a
 * Uint16Array object which will have the following properties:
 *
 *   - length: 25             (length in Uint16 elements)
 *   - byteLength: 50         (length in bytes)
 *   - byteOffset: 100        (byte offset to start of slice)
 *   - BYTES_PER_ELEMENT: 2   (Uint16)
 */

duk_push_buffer_object(ctx, idx_plain_buf, 100, 50, DUK_BUFOBJ_UINT16ARRAY);

.duk_push_c_function() 1.0.0 stack function §

原型 §

duk_idx_t duk_push_c_function(duk_context *ctx, duk_c_function func, duk_idx_t nargs);

堆栈 §

[ . . . ] [ . . . func ]

摘要 §

Push a new function object, associated with a C function, to the stack. The function object is an Ecmascript function object; when called, func will be called using the Duktape/C function interface. Returns non-negative index (relative to stack bottom) of the pushed function.

The nargs argument controls how the value stack looks like when func is entered:

  • If nargs 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 undefined values. Upon entry to the function, value stack top will always match nargs.
  • If nargs is set to DUK_VARARGS, the value stack will contain actual (variable) call arguments and the function needs to check actual argument count with duk_get_top().

The function created will be callable both as a normal function (func()) and as a constructor (new func()). You can differentiate between the two call styles using duk_is_constructor_call(). Although the function can be used as a constructor, it doesn't have an automatic prototype property like Ecmascript functions.

If you intend to use the pushed function as a constructor, you should usually create a prototype object and set the prototype property of the function manually.

示例 §

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);
}

.duk_push_c_lightfunc() stack lightfunc function §

原型 §

duk_idx_t duk_push_c_lightfunc(duk_context *ctx, duk_c_function func, duk_idx_t nargs, duk_idx_t length, duk_int_t magic);

堆栈 §

[ . . . ] [ . . . func ]

摘要 §

Push a new lightfunc value, associated with a C function, to the stack. Returns non-negative index (relative to stack bottom) of the pushed lightfunc.

A lightfunc is a tagged value which contains a Duktape/C function pointer and a small set of internal control flags with no related heap allocations. The internal control flags encode the nargs, length, and magic values, which therefore have significant restrictions:

  • nargs must be [0,14] or DUK_VARARGS.
  • length must be [0,15] and maps to the virtual length property of the lightfunc.
  • magic must be [-128,127].

A lightfunc cannot hold any own properties, it only has virtual name and length properties, and inherits further properties from Function.prototype.

The nargs argument controls how the value stack looks like when func is entered, and behaves like for ordinary Duktape/C functions, see duk_push_c_function().

The function created will be callable both as a normal function (func()) and as a constructor (new func()). You can differentiate between the two call styles using duk_is_constructor_call(). Although the function can be used as a constructor, it cannot have a prototype property like normal Function objects.

If you intend to use the pushed lightfunc as a constructor, and want to use a custom prototype object (instead of Object.prototype), the lightfunc must return an object value. The object will then replace the default instance (bound to this) automatically created for the constructor, and will be the value of a new MyLightFunc() expression.

示例 §

duk_idx_t func_idx;

func_idx = duk_push_c_lightfunc(ctx, my_addtwo, 2 /*nargs*/, 2 /*length*/, 0 /*magic*/);

.duk_push_context_dump() 1.0.0 stack debug §

原型 §

void duk_push_context_dump(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . str ]

摘要 §

Push a one-line string summarizing the state of the current activation of context ctx. This is useful for debugging Duktape/C code and is not intended for production use.

The exact dump contents are version specific. The current format includes the stack top (i.e. number of elements on the stack) and prints out the current elements as an array of JX-formatted (Duktape's custom extended JSON format) values. The example below would print something like:

ctx: top=2, stack=[123,"foo"]
You should not leave dump calls in production code.

示例 §

duk_push_int(ctx, 123);
duk_push_string(ctx, "foo");
duk_push_context_dump(ctx);
printf("%s\n", duk_to_string(ctx, -1));
duk_pop(ctx);

.duk_push_current_function() 1.0.0 stack function §

原型 §

void duk_push_current_function(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . func ] (if current function exists)
[ . . . ] [ . . . undefined ] (if no current function)

摘要 §

Push the currently running function to the stack. The value pushed is an Ecmascript Function object. If there is no current function, undefined is pushed instead.

If the current function was called via one or more bound functions or a Proxy object, the function returned from this call is the final, resolved function (not the bound function or the Proxy).

This function allows a C function to gain access to its function object. Since multiple function objects can internally point to the same C function, a function object is a convenient place for function parameterization and can also act as an internal state stash.

示例 §

duk_push_current_function(ctx);

.duk_push_current_thread() 1.0.0 thread stack function borrowed §

原型 §

void duk_push_current_thread(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . thread ] (if current thread exists)
[ . . . ] [ . . . undefined ] (if no current thread)

摘要 §

Push the currently running Duktape thread to the stack. The value pushed is a thread object which is also an Ecmascript object. If there is no current thread, undefined is pushed instead.

The current thread is (almost always) the thread represented by the ctx pointer.

To get the duk_context * associated with the thread, use duk_get_context().

示例 §

duk_push_thread(ctx);

.duk_push_dynamic_buffer() 1.0.0 stack buffer §

原型 §

void *duk_push_dynamic_buffer(duk_context *ctx, duk_size_t size);

堆栈 §

[ . . . ] [ . . . buf ]

摘要 §

Allocate a dynamic (resizable) buffer and push it to the value stack. Shortcut for duk_push_buffer() with dynamic = 1.

示例 §

void *p;

p = duk_push_dynamic_buffer(ctx, 1024);
printf("allocated buffer, data area: %p\n", p);

.duk_push_error_object() 1.0.0 stack object error §

原型 §

duk_idx_t duk_push_error_object(duk_context *ctx, duk_errcode_t err_code, const char *fmt, ...);

堆栈 §

[ . . . ] [ . . . err ]

摘要 §

Create a new error object and push it to the value stack (the error is not thrown). Returns non-negative index (relative to stack bottom) of the pushed error object.

The message property of the error object will be set to a sprintf-formatted string using fmt and the remaining arguments. The internal prototype for the created error object is chosen based on err_code. For instance, DUK_ERR_RANGE_ERROR causes the built-in RangeError prototype to be used. The valid range for user error codes is [1,16777215].

示例 §

duk_idx_t err_idx;

err_idx = duk_push_error_object(ctx, DUK_ERR_TYPE_ERROR, "invalid argument value: %d", arg_value);

.duk_push_error_object_va() 1.1.0 vararg stack object error §

原型 §

duk_idx_t duk_push_error_object_va(duk_context *ctx, duk_errcode_t err_code, const char *fmt, va_list ap);

堆栈 §

[ . . . ] [ . . . err ]

摘要 §

Vararg variant of duk_push_error_object().

示例 §

duk_idx_t my_type_error(duk_context *ctx, const char *fmt, ...) {
    va_list ap;
    duk_idx_t err_idx;

    va_start(ap, fmt);
    err_idx = duk_push_error_object_va(ctx, DUK_ERR_TYPE_ERROR, fmt, ap);
    va_end(ap);

    return err_idx;
}

.duk_push_external_buffer() 1.3.0 stack buffer §

原型 §

void duk_push_external_buffer(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . buf ]

摘要 §

Allocate an external buffer and push it to the value stack. An external buffer refers to a user allocated external buffer which is not memory managed by Duktape. The initial external buffer pointer is NULL and size is zero. You can use duk_config_buffer() to update the external buffer pointer and size.

External buffers are useful to allow Ecmascript code access externally allocated data structures. You can use it to e.g. write bytes to an externally allocated frame buffer. The external buffer has no alignment requirements (Duktape makes no alignment assumptions when accessing it).

示例 §

void *p;
duk_size_t len;

/* Allocate a frame buffer from a hypothetical graphics library.
 * The frame buffer is allocated outside of Duktape.
 */
p = allocate_frame_buffer(1920 /*width*/, 1080 /*height*/);
len = 1920 * 1080 * 4;

/* Create an external buffer pointing to the frame buffer. */
duk_push_external_buffer(ctx);
duk_config_buffer(ctx, -1, p, len);

/* Ecmascript code with access to the buffer object could now do
 * something like:
 *
 *    buf[100] = 123;
 *
 * Calling code must make sure Ecmascript never reads/writes an
 * external buffer whose backing buffer is no longer valid.
 */

请参阅 §


.duk_push_false() 1.0.0 stack §

原型 §

void duk_push_false(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . false ]

摘要 §

Push false to stack. Equivalent to calling duk_push_boolean(ctx, 0).

示例 §

duk_push_false(ctx);

.duk_push_fixed_buffer() 1.0.0 stack buffer §

原型 §

void *duk_push_fixed_buffer(duk_context *ctx, duk_size_t size);

堆栈 §

[ . . . ] [ . . . buf ]

摘要 §

Allocate a fixed size buffer and push it to the value stack. Shortcut for duk_push_buffer() with dynamic = 0.

示例 §

void *p;

p = duk_push_fixed_buffer(ctx, 1024);
printf("allocated buffer, data area: %p\n", p);

.duk_push_global_object() 1.0.0 stack object §

原型 §

void duk_push_global_object(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . global ]

摘要 §

Push the global object to the stack.

示例 §

duk_push_global_object(ctx);

.duk_push_global_stash() 1.0.0 stash stack sandbox object module §

原型 §

void duk_push_global_stash(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . stash ]

摘要 §

Push the global stash object to the stack. The global stash is an internal object which can be used to store key/value pairs from C code so that they are reachable for garbage collection, but are not accessible from Ecmascript code. The stash is only accessible from C code with a ctx argument associated with the same global object.

示例 §

duk_ret_t set_timer_callback(duk_context *ctx) {
    duk_push_global_stash(ctx);
    duk_dup(ctx, 0);  /* timer callback */
    duk_put_prop_string(ctx, -2, "timerCallback");
    return 0;
}

.duk_push_heap_stash() 1.0.0 stash stack sandbox object module §

原型 §

void duk_push_heap_stash(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . stash ]

摘要 §

Push the heap stash object to the stack. The heap stash is an internal object which can be used to store key/value pairs from C code so that they are reachable for garbage collection, but are not accessible from Ecmascript code. The stash is only accessible from C code; the same stash object is used by all code sharing the same Duktape heap (even if they don't share the same global object).

示例 §

duk_push_heap_stash(ctx);

.duk_push_heapptr() 1.1.0 stack object borrowed §

原型 §

duk_idx_t duk_push_heapptr(duk_context *ctx, void *ptr);

堆栈 §

[ . . . ] [ . . . obj ]

摘要 §

Push a Duktape heap allocated object into the value stack based on a borrowed void pointer reference. The argument ptr must be obtained using duk_get_heapptr() (or its variants) and must have been reachable for Duktape garbage collection up to this call. If ptr is NULL, undefined is pushed.

示例 §

void *ptr;
duk_idx_t idx;

/* 'ptr' originally obtained using duk_get_heapptr() earlier, with the original
 * value reachable by Duktape GC all the way to here:
 */

idx = duk_push_heapptr(ctx, ptr);

.duk_push_int() 1.0.0 stack §

原型 §

void duk_push_int(duk_context *ctx, duk_int_t val);

堆栈 §

[ . . . ] [ . . . val ]

摘要 §

Convert val to an IEEE double and push it to the stack.

This is a shorthand for calling duk_push_number(ctx, (duk_double_t) val).

示例 §

duk_push_int(ctx, 123);

.duk_push_lstring() 1.0.0 string stack §

原型 §

const char *duk_push_lstring(duk_context *ctx, const char *str, duk_size_t len);

堆栈 §

[ . . . ] [ . . . str ]

摘要 §

Push a string of explicit length to the stack. The string may contain arbitrary data, including internal NUL characters. A pointer to the interned string data is returned. If the operation fails, throws an error.

If str is NULL, an empty string is pushed to the stack (regardless of what len is) and a non-NULL pointer to an empty string is returned. The returned pointer can be dereferenced and a NUL terminator character is guaranteed. This behavior differs from duk_push_string on purpose.

C code should normally only push valid CESU-8 strings to the stack.

示例 §

const char tmp1[5] = { 'f', '\0', '\0', 'x', 'y' };
const char tmp2[1] = { '\0' };

duk_push_lstring(ctx, tmp1, 5);   /* push the string "f\x00\x00xy" */
duk_push_lstring(ctx, tmp2, 1);   /* push the string "\x00" */
duk_push_lstring(ctx, tmp2, 0);   /* push empty string */
duk_push_lstring(ctx, NULL, 0);   /* push empty string */
duk_push_lstring(ctx, NULL, 10);  /* push empty string */

.duk_push_nan() 1.0.0 stack §

原型 §

void duk_push_nan(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . NaN ]

摘要 §

Pushes a <code>NaN</code> (not-a-number) to the stack.

示例 §

duk_push_nan(ctx);

printf("NaN is number: %d\n", (int) duk_is_number(ctx, -1));

.duk_push_null() 1.0.0 stack §

原型 §

void duk_push_null(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . null ]

摘要 §

Push null to the stack.

示例 §

duk_push_null(ctx);

.duk_push_number() 1.0.0 stack §

原型 §

void duk_push_number(duk_context *ctx, duk_double_t val);

堆栈 §

[ . . . ] [ . . . val ]

摘要 §

Push number (IEEE double) val to the stack.

If val is a NaN it may be normalized into another NaN form.

示例 §

duk_push_number(ctx, 123.0);

.duk_push_object() 1.0.0 stack object §

原型 §

duk_idx_t duk_push_object(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . obj ]

摘要 §

Push an empty object to the stack. Returns non-negative index (relative to stack bottom) of the pushed object.

The internal prototype of the created object is Object.prototype. Use duk_set_prototype() to change it.

示例 §

duk_idx_t obj_idx;

obj_idx = duk_push_object(ctx);
duk_push_int(ctx, 42);
duk_put_prop_string(ctx, obj_idx, "meaningOfLife");

/* object is now: { "meaningOfLife": 42 } */

duk_pop(ctx);  /* pop object */

.duk_push_pointer() 1.0.0 stack §

原型 §

void duk_push_pointer(duk_context *ctx, void *p);

堆栈 §

[ . . . ] [ . . . ptr ]

摘要 §

Push p into the stack as a pointer value. Duktape won't interpret the pointer in any manner.

示例 §

struct mystruct *p = /* ... */;

duk_push_pointer(ctx, (void *) p);

.duk_push_sprintf() 1.0.0 string stack §

原型 §

const char *duk_push_sprintf(duk_context *ctx, const char *fmt, ...);

堆栈 §

[ . . . ] [ . . . str ]

摘要 §

Format a string like sprintf() (but safely) and push the result to the value stack. Returns a non-NULL pointer to the resulting string.

If fmt is NULL, an empty string is pushed to the stack and a non-NULL pointer to an empty string is returned (this behavior mimics what sprintf() does for a NULL format string, at least on Linux). The returned pointer can be dereferenced and a NUL terminator character is guaranteed.

Unlike sprintf() the string formatting is safe with respect to result length. Concretely, the implementation will try increasing temporary buffer sizes until a large enough buffer is found for the temporary formatted value.

There may be platform specific behavior for some format specifiers. For example, the behavior of %s with a NULL argument has officially undefined behavior, so actual behavior may vary across platforms and may even be memory unsafe.

示例 §

duk_push_sprintf(ctx, "meaning of life: %d, name: %s", 42, "Zaphod");

.duk_push_string() 1.0.0 string stack §

原型 §

const char *duk_push_string(duk_context *ctx, const char *str);

堆栈 §

[ . . . ] [ . . . str ] (if str != NULL)
[ . . . ] [ . . . null ] (if str == NULL)

摘要 §

Push a C string into the stack. String length is automatically detected with a strlen() equivalent (i.e. looking for the first NUL character). A pointer to the interned string data is returned. If the operation fails, throws an error.

If str is NULL, an Ecmascript null is pushed to the stack and NULL is returned. This behavior differs from duk_push_lstring on purpose.

C code should normally only push valid CESU-8 strings to the stack. Some invalid CESU-8/UTF-8 byte sequences are reserved for special uses such as representing Symbol values. When you push such an invalid byte sequence, the value on the value stack will behave like a string for C code but will appear as a Symbol for Ecmascript code. See Symbols for more discussion.

If input string might contain internal NUL characters, use duk_push_lstring() instead.

示例 §

duk_push_string(ctx, "foo");
duk_push_string(ctx, "foo\0bar");  /* push "foo", not "foo\0bar" */
duk_push_string(ctx, "");          /* push empty string */
duk_push_string(ctx, NULL);        /* push 'null' */

.duk_push_this() 1.0.0 stack function §

原型 §

void duk_push_this(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . this ]

摘要 §

Push the this binding of the currently running C function to the stack.

示例 §

duk_push_this(ctx);

.duk_push_thread() 1.0.0 thread stack borrowed §

原型 §

duk_idx_t duk_push_thread(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . thr ]

摘要 §

Push a new Duktape thread (context, coroutine) to the stack. Returns non-negative index (relative to stack bottom) of the pushed thread. The new thread will be associated with the same Duktape heap as the argument ctx, and will share the same global object environment.

To interact with the new thread with the Duktape API, use duk_get_context() to get a context pointer for API calls.

示例 §

duk_idx_t thr_idx;
duk_context *new_ctx;

thr_idx = duk_push_thread(ctx);
new_ctx = duk_get_context(ctx, thr_idx);

.duk_push_thread_new_globalenv() 1.0.0 thread stack borrowed §

原型 §

duk_idx_t duk_push_thread_new_globalenv(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . thr ]

摘要 §

Push a new Duktape thread (context, coroutine) to the stack. Returns non-negative index (relative to stack bottom) of the pushed thread. The new thread will be associated with the same Duktape heap as the argument ctx, but will have a new global object environment (separate from the one used by ctx).

To interact with the new thread with the Duktape API, use duk_get_context() to get a context pointer for API calls.

示例 §

duk_idx_t thr_idx;
duk_context *new_ctx;

thr_idx = duk_push_thread_new_globalenv(ctx);
new_ctx = duk_get_context(ctx, thr_idx);

请参阅 §


.duk_push_thread_stash() 1.0.0 thread stash stack sandbox object module §

原型 §

void duk_push_thread_stash(duk_context *ctx, duk_context *target_ctx);

堆栈 §

[ . . . ] [ . . . stash ]

摘要 §

Push the stash object related to target_ctx to the stack (the ctx and target_ctx arguments may refer to the same thread). The thread stash is an internal object which can be used to store key/value pairs from C code so that they are reachable for garbage collection, but are not accessible from Ecmascript code. The stash is only accessible from C code with a matching target_ctx argument.

If target_ctx is NULL, throws an error.

示例 §

duk_push_thread_stash(ctx, ctx2);

.duk_push_true() 1.0.0 stack §

原型 §

void duk_push_true(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . true ]

摘要 §

Push true to stack. Equivalent to calling duk_push_boolean(ctx, 1).

示例 §

duk_push_true(ctx);

.duk_push_uint() 1.0.0 stack §

原型 §

void duk_push_uint(duk_context *ctx, duk_uint_t val);

堆栈 §

[ . . . ] [ . . . val ]

摘要 §

Convert val to an IEEE double and push it to the stack.

This is a shorthand for calling duk_push_number(ctx, (duk_double_t) val).

示例 §

duk_push_uint(ctx, 123);

.duk_push_undefined() 1.0.0 stack §

原型 §

void duk_push_undefined(duk_context *ctx);

堆栈 §

[ . . . ] [ . . . undefined ]

摘要 §

Push undefined to the stack.

示例 §

duk_push_undefined(ctx);

.duk_push_vsprintf() 1.0.0 vararg string stack §

原型 §

const char *duk_push_vsprintf(duk_context *ctx, const char *fmt, va_list ap);

堆栈 §

[ . . . ] [ . . . str ]

摘要 §

Format a string like vsprintf() (but safely) and push the result value to the value stack. Returns a non-NULL pointer to the resulting string.

If fmt is NULL, an empty string is pushed to the stack and a non-NULL pointer to an empty string is returned (this behavior mimics what vsprintf() does for a NULL format string, at least on Linux). The returned pointer can be dereferenced and a NUL terminator character is guaranteed.

Unlike vsprintf() the string formatting is safe. Concretely, the implementation will try increasing temporary buffer sizes until a large enough buffer is found for the temporary formatted value.

The ap argument cannot be safely reused for multiple calls. This is a limitation of the vararg mechanism.

示例 §

void test_vsprintf(duk_context *ctx, ...) {
    va_list ap;

    va_start(ap, ctx);
    duk_push_vsprintf(ctx, "test: %d+%d=%d", ap);
    va_end(ap);
}

void test(duk_context *ctx) {
    test_vsprintf(ctx, 2, 3, 5);
}

.duk_put_function_list() 1.0.0 property module §

原型 §

void duk_put_function_list(duk_context *ctx, duk_idx_t obj_idx, const duk_function_list_entry *funcs);

堆栈 §

[ . . . obj . . . ] [ . . . obj . . . ]

摘要 §

Set multiple function properties into a target object at obj_idx. The functions are specified as a list of triples (name, function, nargs), ending with a triple where name is NULL (preferably also function is NULL for sanity).

This is useful e.g. when defining modules or classes implemented as a set of Duktape/C functions.

示例 §

const duk_function_list_entry my_module_funcs[] = {
    { "tweak", do_tweak, 0 /* no args */ },
    { "adjust", do_adjust, 3 /* 3 args */ },
    { "frobnicate", do_frobnicate, DUK_VARARGS /* variable args */ },
    { NULL, NULL, 0 }
};

/* Initialize an object with a set of function properties, and set it to
 * global object 'MyModule'.
 */

duk_push_global_object(ctx);
duk_push_object(ctx);  /* -> [ ... global obj ] */
duk_put_function_list(ctx, -1, my_module_funcs);
duk_put_prop_string(ctx, -2, "MyModule");  /* -> [ ... global ] */
duk_pop(ctx);

.duk_put_global_lstring() 2.0.0 property §

原型 §

duk_bool_t duk_put_global_lstring(duk_context *ctx, const char *key, duk_size_t key_len);

堆栈 §

[ . . . val ] [ . . . ]

摘要 §

Like duk_put_global_string() but the key is given as a string with explicit length.

示例 §

duk_push_string(ctx, "1.2.3");
(void) duk_put_global_lstring(ctx, "internal" "\x00" "nul");

.duk_put_global_string() 1.0.0 property §

原型 §

duk_bool_t duk_put_global_string(duk_context *ctx, const char *key);

堆栈 §

[ . . . val ] [ . . . ]

摘要 §

Put property named key to the global object. Return value behaves similarly to duk_put_prop(). This is a convenience function which does the equivalent of:

duk_bool_t ret;

duk_push_global_object(ctx);
duk_insert(ctx, -2);
ret = duk_put_prop_string(ctx, -2, key);
duk_pop(ctx);
/* 'ret' would be the return value from duk_put_global_string() */

示例 §

duk_push_string(ctx, "1.2.3");
(void) duk_put_global_string(ctx, "my_app_version");

.duk_put_number_list() 1.0.0 property module §

原型 §

void duk_put_number_list(duk_context *ctx, duk_idx_t obj_idx, const duk_number_list_entry *numbers);

堆栈 §

[ . . . obj . . . ] [ . . . obj . . . ]

摘要 §

Set multiple number (double) properties into a target object at obj_idx. The number list is given as a list of pairs (name, number), ending with a pair where the name is NULL.

This is useful e.g. when defining numeric constants for modules or classes implemented in C.

示例 §

const duk_number_list_entry my_module_consts[] = {
    { "FLAG_FOO", (double) (1 << 0) },
    { "FLAG_BAR", (double) (1 << 1) },
    { "FLAG_QUUX", (double) (1 << 2) },
    { "DELAY", 300.0 },
    { NULL, 0.0 }
};

duk_put_number_list(ctx, -3, my_module_consts);

.duk_put_prop() 1.0.0 property §

原型 §

duk_bool_t duk_put_prop(duk_context *ctx, duk_idx_t obj_idx);

堆栈 §

[ . . . obj . . . key val ] [ . . . obj . . . ]

摘要 §

Write val to the property key of a value at obj_idx. key and val are removed from the stack. Return code and error throwing behavior:

  • If the property write succeeds, returns 1.
  • If the property write fails, throws an error (strict mode semantics). An error may also be thrown by the "setter" function of an accessor property.
  • If the value at obj_idx is not object coercible, throws an error.
  • If obj_idx is invalid, throws an error.

The property write is equivalent to the Ecmascript expression obj[key] = val. The exact rules of when a property write succeeds or fails are the same as for Ecmascript code making the equivalent assignment. For precise semantics, see Property Accessors, PutValue (V, W), and [[Put]] (P, V, Throw). Both the target value and the key are coerced:

  • The target value is automatically coerced to an object. However, the object is transitory so writing its properties is not very useful. Moreover, Ecmascript semantics prevent new properties from being created for such transitory objects (see PutValue (V, W), step 7 of the special [[Put]] variant).
  • The key argument is internally coerced using ToPropertyKey() coercion which results in a string or a Symbol. There is an internal fast path for arrays and numeric indices which avoids an explicit string coercion, so use a numeric key when applicable.

If the target is a Proxy object which implements the set trap, the trap is invoked and the API call return value matches the trap return value.

In Ecmascript an assignment expression has the value of the right-hand-side expression, regardless of whether or not the assignment succeeds. The return value for this API call is not specified by Ecmascript or available to Ecmascript code: the API call returns 0 or 1 depending on whether the assignment succeeded or not (with the 0 return value promoted to an error in strict code).

If the key is a fixed string you can avoid one API call and use the duk_put_prop_string() variant. Similarly, if the key is an array index, you can use the duk_put_prop_index() variant.

Although the base value for property accesses is usually an object, it can technically be an arbitrary value. Plain string and buffer values have virtual index properties so you can access "foo"[2], for instance. Most primitive values also inherit from some prototype object so that you can e.g. call methods on them: (12345).toString(16).

示例 §

duk_bool_t rc;

duk_push_string(ctx, "key");
duk_push_string(ctx, "value");
rc = duk_put_prop(ctx, -3);
printf("rc=%d\n", (int) rc);

.duk_put_prop_index() 1.0.0 property §

原型 §

duk_bool_t duk_put_prop_index(duk_context *ctx, duk_idx_t obj_idx, duk_uarridx_t arr_idx);

堆栈 §

[ . . . obj . . . val ] [ . . . obj . . . ]

摘要 §

Like duk_put_prop(), but the property name is given as an unsigned integer arr_idx. This is especially useful for writing to array elements (but is not limited to that).

Conceptually the number is coerced to a string for the property write, e.g. 123 would be equivalent to a property name "123". Duktape avoids an explicit coercion whenever possible.

示例 §

duk_push_string(ctx, "value");
rc = duk_put_prop_index(ctx, -3, 123);  /* write to obj[123] */
printf("rc=%d\n", (int) rc);

.duk_put_prop_lstring() 2.0.0 property §

原型 §

duk_bool_t duk_put_prop_lstring(duk_context *ctx, duk_idx_t obj_idx, const char *key, duk_size_t key_len);

堆栈 §

[ . . . obj . . . val ] [ . . . obj . . . ]

摘要 §

Like duk_put_prop(), but the property name is given as a string with explicit length.

示例 §

duk_bool_t rc;

duk_push_string(ctx, "value");
rc = duk_put_prop_lstring(ctx, -3, "internal" "\x00" "nul", 12);
printf("rc=%d\n", (int) rc);

.duk_put_prop_string() 1.0.0 property §

原型 §

duk_bool_t duk_put_prop_string(duk_context *ctx, duk_idx_t obj_idx, const char *key);

堆栈 §

[ . . . obj . . . val ] [ . . . obj . . . ]

摘要 §

Like duk_put_prop(), but the property name is given as a NUL-terminated C string key.

示例 §

duk_bool_t rc;

duk_push_string(ctx, "value");
rc = duk_put_prop_string(ctx, -3, "key");
printf("rc=%d\n", (int) rc);

.duk_range_error() 2.0.0 error §

原型 §

duk_ret_t duk_range_error(duk_context *ctx, const char *fmt, ...);

堆栈 §

[ . . . ] [ . . . err ]

摘要 §

Convenience API call, equivalent to duk_error() with an error code DUK_ERR_RANGE_ERROR.

示例 §

return duk_range_error(ctx, "my error: %d", (int) argval);

请参阅 §


.duk_range_error_va() 2.0.0 vararg error §

原型 §

duk_ret_t duk_range_error_va(duk_context *ctx, const char *fmt, va_list ap);

堆栈 §

[ . . . ] [ . . . err ]

摘要 §

Convenience API call, equivalent to duk_error_va() with an error code DUK_ERR_RANGE_ERROR.

示例 §

void my_range_error(duk_context *ctx, const char *fmt, ...) {
    va_list ap;

    va_start(ap, fmt);
    duk_range_error_va(ctx, fmt, ap);
    va_end(ap);
}

请参阅 §


.duk_realloc() 1.0.0 memory §

原型 §

void *duk_realloc(duk_context *ctx, void *ptr, duk_size_t size);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Like duk_realloc_raw() but may trigger a garbage collection to satisfy the request. However, the allocated memory itself is not automatically garbage collected. If allocated size is extended from previous allocation, the newly allocated bytes are not automatically zeroed and may contain arbitrary garbage.

Memory reallocated with duk_realloc() can be freed with either duk_free() or duk_free_raw().

示例 §

void *buf = duk_alloc(ctx, 1024);
if (buf) {
    void *buf2 = duk_realloc(ctx, 2048);
    if (!buf2) {
        printf("failed to reallocate, 'buf' still valid\n");
    } else {
        printf("reallocate successful, 'buf2' now valid\n");
    }
}

请参阅 §


.duk_realloc_raw() 1.0.0 memory §

原型 §

void *duk_realloc_raw(duk_context *ctx, void *ptr, duk_size_t size);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Resize a previous allocation made with the allocation functions registered to the context. The ptr argument points to the previous allocation while size is the new allocation size. The call returns a pointer to the new allocation which may have a different pointer than the previous one. If the reallocation fails, a NULL is returned and the previous allocation is still valid. Reallocation failure should only be possible when the new size is larger than the previous size (i.e. caller tries to grow the allocation). The attempt to reallocate cannot trigger a garbage collection, and the allocated memory is not automatically garbage collected. If allocated size is extended from previous allocation, the newly allocated bytes are not automatically zeroed and may contain arbitrary garbage.

The exact behavior depends on the ptr and size arguments as follows:

  • If ptr is non-NULL and size is greater than zero, previous allocation is resized.
  • If ptr is non-NULL and size is zero, the call is equivalent to a duk_free_raw().
  • If ptr is NULL, and size is greater than zero, the call is equivalent to a duk_alloc_raw().
  • If ptr is NULL, and size is zero, the call is equivalent to a duk_alloc_raw() with a zero size argument; the call may return NULL or some other value which is safe to give to duk_free_raw().

Memory reallocated with duk_realloc_raw() can be freed with either duk_free() or duk_free_raw().

示例 §

void *buf = duk_alloc_raw(ctx, 1024);
if (buf) {
    void *buf2 = duk_realloc_raw(ctx, 2048);
    if (!buf2) {
        printf("failed to reallocate, 'buf' still valid\n");
    } else {
        printf("reallocate successful, 'buf2' now valid\n");
    }
}

请参阅 §


.duk_reference_error() 2.0.0 error §

原型 §

duk_ret_t duk_reference_error(duk_context *ctx, const char *fmt, ...);

堆栈 §

[ . . . ] [ . . . err ]

摘要 §

Convenience API call, equivalent to duk_error() with an error code DUK_ERR_REFERENCE_ERROR.

示例 §

return duk_reference_error(ctx, "my error: %d", (int) argval);

请参阅 §


.duk_reference_error_va() 2.0.0 vararg error §

原型 §

duk_ret_t duk_reference_error_va(duk_context *ctx, const char *fmt, va_list ap);

堆栈 §

[ . . . ] [ . . . err ]

摘要 §

Convenience API call, equivalent to duk_error_va() with an error code DUK_ERR_REFERENCE_ERROR.

示例 §

void my_reference_error(duk_context *ctx, const char *fmt, ...) {
    va_list ap;

    va_start(ap, fmt);
    duk_reference_error_va(ctx, fmt, ap);
    va_end(ap);
}

请参阅 §


.duk_remove() 1.0.0 stack §

原型 §

void duk_remove(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val(idx) . . . ] [ . . . . . . ]

摘要 §

Remove value at idx. Elements above idx are shifted down the stack by a step. If idx is an invalid index, throws an error.

示例 §

duk_push_int(ctx, 123);
duk_push_int(ctx, 234);
duk_push_int(ctx, 345);       /* -> [ 123 234 345 ] */
duk_remove(ctx, -2);          /* -> [ 123 345 ] */

.duk_replace() 1.0.0 stack §

原型 §

void duk_replace(duk_context *ctx, duk_idx_t to_idx);

堆栈 §

[ . . . old(to_idx) . . . val ] [ . . . val(to_idx) . . . ]

摘要 §

Replace value at to_idx with a value popped from the stack top. If to_idx is an invalid index, throws an error.

Negative indices are evaluated prior to popping the value at the stack top. This is also illustrated by the example.

示例 §

duk_push_int(ctx, 123);
duk_push_int(ctx, 234);
duk_push_int(ctx, 345);       /* -> [ 123 234 345 ] */
duk_push_string(ctx, "foo");  /* -> [ 123 234 345 "foo" ] */
duk_replace(ctx, -3);         /* -> [ 123 "foo" 345 ] */

请参阅 §


.duk_require_boolean() 1.0.0 stack §

原型 §

duk_bool_t duk_require_boolean(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Like duk_get_boolean(), but throws an error if the value at idx is not a boolean or if the index is invalid.

示例 §

if (duk_require_boolean(ctx, -3)) {
    printf("value is true\n");
}

.duk_require_buffer() 1.0.0 stack buffer §

原型 §

void *duk_require_buffer(duk_context *ctx, duk_idx_t idx, duk_size_t *out_size);

堆栈 §

[ . . . val . . . ]

摘要 §

Like duk_get_buffer(), but throws an error if the value at idx is not a (plain) buffer or if the index is invalid.

示例 §

void *ptr;
duk_size_t sz;

ptr = duk_require_buffer(ctx, -3, &sz);
printf("buf=%p, size=%lu\n", ptr, (unsigned long) sz);

.duk_require_buffer_data() 1.3.0 stack bufferobject buffer §

原型 §

void *duk_require_buffer_data(duk_context *ctx, duk_idx_t idx, duk_size_t *out_size);

堆栈 §

[ . . . val . . . ]

摘要 §

Like duk_get_buffer_data(), but throws an error if the value at idx is not a plain buffer or a buffer object or if the index is invalid.

示例 §

void *ptr;
duk_size_t sz;

ptr = duk_require_buffer_data(ctx, -3, &sz);
printf("buf=%p, size=%lu\n", ptr, (unsigned long) sz);

.duk_require_c_function() 1.0.0 stack function §

原型 §

duk_c_function duk_require_c_function(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Like duk_get_c_function(), but throws an error if the value at idx is not an Ecmascript function associated with a Duktape/C function or if the index is invalid.

示例 §

duk_c_function funcptr;

funcptr = duk_require_c_function(ctx, -3);

.duk_require_callable() 1.4.0 stack §

原型 §

void duk_require_callable(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Throw an error if the value at idx is not callable or if the index is invalid.

There is no "get" primitive (duk_get_callable()) because there's no useful C return value for an arbitrary callable value. At the moment this call is equivalent to calling duk_require_function().

示例 §

duk_require_callable(ctx, -3);

.duk_require_context() 1.0.0 stack borrowed §

原型 §

duk_context *duk_require_context(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Like duk_get_context(), but throws an error if the value at idx is not a Duktape thread or if the index is invalid.

示例 §

duk_context *new_ctx;

(void) duk_push_thread(ctx);
new_ctx = duk_require_context(ctx, -1);

.duk_require_function() 1.4.0 stack §

原型 §

void duk_require_function(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Throw an error if the value at idx is not a function or if the index is invalid.

There is no "get" primitive (duk_get_function()) because there's no useful C return value for an arbitrary function.

示例 §

duk_require_function(ctx, -3);

.duk_require_heapptr() 1.1.0 stack borrowed §

原型 §

void *duk_require_heapptr(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Like duk_get_heapptr(), but throws an error if the value at idx is not a Duktape heap allocated value (object, buffer, string) or if the index is invalid.

示例 §

void *ptr;

ptr = duk_require_heapptr(ctx, -3);

.duk_require_int() 1.0.0 stack §

原型 §

duk_int_t duk_require_int(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Like duk_get_int(), but throws an error if the value at idx is not a number or if the index is invalid.

示例 §

printf("int value: %ld\n", (long) duk_require_int(ctx, -3));

.duk_require_lstring() 1.0.0 string stack §

原型 §

const char *duk_require_lstring(duk_context *ctx, duk_idx_t idx, duk_size_t *out_len);

堆栈 §

[ . . . val . . . ]

摘要 §

Like duk_get_lstring(), but throws an error if the value at idx is not a string or if the index is invalid.

示例 §

const char *buf;
duk_size_t len;

buf = duk_require_lstring(ctx, -3, &len);
printf("value is a string, %lu bytes\n", (unsigned long) len);

.duk_require_normalize_index() 1.0.0 stack §

原型 §

duk_idx_t duk_require_normalize_index(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Normalize argument index relative to the bottom of the current frame. The resulting index will be 0 or greater and will be independent of later stack modifications. If the input index is invalid, throws an error.

示例 §

duk_idx_t idx = duk_require_normalize_index(-3);

.duk_require_null() 1.0.0 stack §

原型 §

void duk_require_null(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Throw an error if the value at idx is not null or if the index is invalid.

There is no "get" primitive (duk_get_null()) because such a function would be a no-op.

示例 §

duk_require_null(ctx, -3);

.duk_require_number() 1.0.0 stack §

原型 §

duk_double_t duk_require_number(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Like duk_get_number(), but throws an error if the value at idx is not a number or if the index is invalid.

示例 §

printf("value: %lf\n", (double) duk_require_number(ctx, -3));

.duk_require_object_coercible() 1.0.0 stack object §

原型 §

void duk_require_object_coercible(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Like duk_is_object_coercible() but throws a TypeError if val is not object coercible.

示例 §

duk_require_object_coercible(ctx, -3);

.duk_require_pointer() 1.0.0 stack §

原型 §

void *duk_require_pointer(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Like duk_get_pointer(), but throws an error if the value at idx is not a pointer or if the index is invalid.

示例 §

void *ptr;

ptr = duk_require_pointer(ctx, -3);
printf("my pointer is: %p\n", ptr);

.duk_require_stack() 1.0.0 stack §

原型 §

void duk_require_stack(duk_context *ctx, duk_idx_t extra);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Like duk_check_stack() but an error is thrown if the value stack needs to be reallocated and that reallocation fails.

As a general rule, callers should use this function to reserve more stack space. If value stack cannot be extended, there is almost never a useful recovery strategy except to throw an error and unwind.

示例 §

duk_idx_t nargs;

nargs = duk_get_top(ctx);  /* number or arguments */

/* reserve space for one temporary for each input argument */
duk_require_stack(ctx, nargs * 2);

请参阅 §


.duk_require_stack_top() 1.0.0 stack §

原型 §

void duk_require_stack_top(duk_context *ctx, duk_idx_t top);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Like duk_check_stack_top() but an error is thrown if the value stack needs to be reallocated and that reallocation fails.

As a general rule, callers should use this function to reserve more stack space. If value stack cannot be extended, there is almost never a useful recovery strategy except to throw an error and unwind.

示例 §

duk_require_stack_top(ctx, 100);
printf("value stack guaranteed up to index 99\n");

.duk_require_string() 1.0.0 string stack §

原型 §

const char *duk_require_string(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Like duk_get_string(), but throws an error if the value at idx is not a string or if the index is invalid.

Symbol values are visible in the C API as strings so that both duk_is_symbol() and duk_is_string() are true. This behavior is similar to Duktape 1.x internal strings. Symbols are still an experimental feature; for now, you can distinguish Symbols from ordinary strings using duk_is_symbol(). For the internal representation, see symbols.rst.

示例 §

const char *buf;

buf = duk_require_string(ctx, -3);
printf("value is a string: %s\n", buf);

.duk_require_top_index() 1.0.0 stack §

原型 §

duk_idx_t duk_require_top_index(duk_context *ctx);

堆栈 §

(对值堆栈没有影响。)

摘要 §

Get the absolute index (>= 0) of the topmost value on the stack. If the stack is empty, throws an error.

示例 §

duk_idx_t idx_top;

/* throws error if stack is empty */
idx_top = duk_require_top_index(ctx);
printf("index of top element: %ld\n", (long) idx_top);

请参阅 §


.duk_require_type_mask() 1.0.0 stack §

原型 §

void duk_require_type_mask(duk_context *ctx, duk_idx_t idx, duk_uint_t mask);

堆栈 §

[ . . . val . . . ]

摘要 §

Like duk_check_type_mask() but throws a TypeError if val type does not match any of the mask bits.

示例 §

duk_require_type_mask(ctx, -3, DUK_TYPE_MASK_STRING |
                               DUK_TYPE_MASK_NUMBER);

.duk_require_uint() 1.0.0 stack §

原型 §

duk_uint_t duk_require_uint(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Like duk_get_uint(), but throws an error if the value at idx is not a number or if the index is invalid.

示例 §

printf("unsigned int value: %lu\n", (unsigned long) duk_require_uint(ctx, -3));

.duk_require_undefined() 1.0.0 stack §

原型 §

void duk_require_undefined(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Throw an error if the value at idx is not undefined or if the index is invalid.

There is no "get" primitive (duk_get_undefined()) because such a function would be a no-op.

示例 §

duk_require_undefined(ctx, -3);

.duk_require_valid_index() 1.0.0 stack §

原型 §

void duk_require_valid_index(duk_context *ctx, duk_idx_t idx);

堆栈 §

[ . . . val . . . ]

摘要 §

Validate argument index. Throw an error if index is valid, return (without a return value) otherwise.

示例 §

duk_require_valid_index(ctx, -3);
printf("index -3 is valid\n");

.duk_resize_buffer() 1.0.0 stack buffer §

原型 §

void *duk_resize_buffer(duk_context *ctx, duk_idx_t idx, duk_size_t new_size);

堆栈 §

[ . . . val . . . ]

摘要 §

Resize a dynamic buffer at idx to new_size bytes. If new_size is larger than the current size, newly allocated bytes (above old size) are automatically zeroed. Returns a pointer to the new buffer data area. If new_size is zero, may return either NULL or some non-NULL value. If resizing fails, the value at idx is not a dynamic buffer, or idx is invalid, throws an error.

示例 §

void *ptr;

ptr = duk_resize_buffer(ctx, -3, 4096);

.duk_resume() 1.6.0 thread §

原型 §

void duk_resume(duk_context *ctx,