gpt4 book ai didi

c++ - 迭代 Duktape 中的未知对象

转载 作者:行者123 更新时间:2023-11-30 03:33:31 25 4
gpt4 key购买 nike

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

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

我正在尝试将此类对象转换为 C++ std::map<string, string>例如,从 Javascript 调用 myFunction({x: 1, y: 3, z: 35})应该和myFunction({foo: 12, bar: 43})一样有效.

似乎duk_enum()将是一个合适的功能,但我不太了解它是如何工作的。

最佳答案

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. */

如果您不想自动推送值,请将 0 传递给 duk_next() 的“get_value”参数,并在循环结束时仅弹出键。

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

关于c++ - 迭代 Duktape 中的未知对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42805075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com