これは基本的にオブジェクトの配列が長いため、配列としてパラメータを複数回JavaScript関数を呼び出す必要があります。私はすでに関数を呼び出すたびにリストを再作成しても、配列をDuktapeスタックの先頭に移動しようとすると、期待通りに機能しませんでした。たぶん私はあなたが見ることができるように、一番下に私が先頭に配列を移動するためにduk_swap_top(ctx, arr_idx)
を呼び出そうと...完全に間違ってトラックに関数を2回実行する
duk_context* ctx(duk_create_heap_default());
duk_push_c_function(ctx, nativePrint, DUK_VARARGS);
duk_put_global_string(ctx, "print");
/// Define the function the first time
duk_eval_string(ctx, "function func(entries, targetEntry) { print(targetEntry, JSON.stringify(entries)); return 404; }");
duk_get_global_string(ctx, "func");
/// Define lambdas to create the array
auto pushObject = [&]() {
duk_idx_t obj_idx;
obj_idx = duk_push_object(ctx);
duk_push_int(ctx, 42);
duk_put_prop_string(ctx, obj_idx, "meaningOfLife");
};
auto pushArray = [&]() {
duk_idx_t arr_idx;
arr_idx = duk_push_array(ctx);
pushObject();
duk_put_prop_index(ctx, arr_idx, 0);
pushObject();
duk_put_prop_index(ctx, arr_idx, 1);
return arr_idx;
};
/// Push the arguments
auto arr_idx = pushArray();
duk_push_number(ctx, 102);
/// Define lambda to call the function
auto processEntry = [&]() {
if (duk_pcall(ctx, 2 /*nargs*/) != 0) {
printf("Error: %s\n", duk_safe_to_string(ctx, -1));
} else {
if (duk_is_number(ctx, -1)) cout << "NumRes: " << duk_get_number(ctx, -1) << endl;
else printf("Res: %s\n", duk_safe_to_string(ctx, -1));
}
duk_pop(ctx);
cout << endl;
};
/// Calling the function the first time
processEntry();
/// Loading the function as the global string again
duk_eval_string(ctx, "function func(entries, targetEntry) { print(targetEntry, JSON.stringify(entries)); return 404; }");
duk_get_global_string(ctx, "func");
/// Attempt to move the array to the top and execute the function
/// Executing pushArray(); again works but not duk_swap_top(...);
// pushArray();
duk_swap_top(ctx, arr_idx);
duk_push_number(ctx, 444);
processEntry();
です。どうやら、それは私が思った通りではなく、代わりにTypeError: undefined not callable
を返します。それを別のpushArray();
と交換すると、期待どおりに動作し、との両方が印刷されます。