迭代Duktape中的一个未知物体

时间:2017-03-15 08:58:10

标签: c++ duktape

所以我有这个duktape函数,它接受一个对象作为参数之一。在正常情况下,要检索每个对象属性的值,我会使用duk_push_string()std::map<string, string>,但这假设我事先知道了我得到的对象的结构。

现在,考虑一个接受具有未知结构的对象的函数。我需要迭代它的键,并检索它的所有值。

我正在尝试将这样的对象转换为C ++ myFunction({x: 1, y: 3, z: 35}) 例如,从Javascript调用 myFunction({foo: 12, bar: 43})应该与duk_enum()一样有用。

DateTime.ParseExact似乎是一个合适的功能,但我不太明白它是如何工作的。

1 个答案:

答案 0 :(得分:2)

duk_enum()的基本习语是:

/* Assume target object to enumerate is at obj_idx.
 * For a function's 1st argument that would be 0.
 */

duk_enum(ctx, 0 /*enum_flags*/);  /* Pushes enumerator object. */
while (duk_next(ctx, -1, 1 /*get_value*/)) {  /* -1 points to enumerator, here top of stack */
    /* Each time duk_enum() finds a new key/value pair, it
     * gets pushed to the value stack.  So here the stack
     * top is [ ... enum key value ].  Enum is at index -3,
     * key at -2, value at -1, all relative to stack top.
     */

    printf("enumerated key '%s', value '%s'\n", duk_safe_to_string(ctx, -2), duk_safe_to_string(ctx, -1));

    /* When you're done with the key/value, pop them off. */
    duk_pop_2(ctx);
}
duk_pop(ctx);  /* Pop enumerator object. */

如果您不想自动推送该值,请为&#34; get_value&#34;传递0; duk_next()的参数,只弹出循环结束时的键。

duk_enum()有一组标志来控制你要枚举的内容。 0对应于&#34; for(var k in obj){...}&#34;枚举。

相关问题