I want to make something with an array in a javasctipt function, but don’t konw how to pass an array into it. Does anyone knows? Thanks…
Have you tried Array<var>
? I don’t think specifically typed Arrays like Array<int>
would work.
No, not yet. I had passed a string to the script by using JavascriptEngine::execute( const String javascriptCode). Does it right?
That doesn’t pass a String to the engine, it’s the JavaScript code you want executed.
Thank you very much.
String defaultFunString = {
"function factorial(n)\n"
"{\n"
" /* do some with n and return a string */;\n"
"\n}"
};
String returnStr = "var str = factorial(\" Hello World \")";
String getStr = "demo.getVar(str)";
jsEngine.execute(defaultFunString + returnStr + getStr);
I use it in this way, maybe I am wrong. In other words, which function can provide or change javascript function’s arguments?
Using the JavaScriptEngine is unfortunately quite involved. Here’s an example :
void test_js_engine()
{
JavascriptEngine je;
// this code doesn't really "execute" anything yet, but it prepares the "test" function
// to be called later from the C++ code
auto r = je.execute(R"(
function test(a)
{
for (i = 0 ; i < 4 ; i++)
{
a[i]=0.5*i;
}
return "done";
}
)");
if (r.failed())
{
// parsing the JavaScript code failed, so no reason to continue further
std::cout << r.getErrorMessage() << "\n";
return;
}
// all this is quite messy, but no way around it...
Array<var> arr{ 0.1,0.444,0.55,-3.33 };
// convert the variant array to a single var
var vararg = arr;
// convert the variant into NativeFunctionArguments
var::NativeFunctionArgs args{ var(),&vararg,1 };
// finally, we can call the JavaScript function!
auto jsresult = je.callFunction("test",args,&r);
if (r.failed())
{
std::cout << r.getErrorMessage() << "\n";
}
else
{
// display the function result string and the modified array
std::cout << jsresult.toString() << "\n";
for (int i=0;i<vararg.size();++i)
std::cout << vararg[i].toString() << " ";
std::cout << "\n";
}
}
2 Likes
Ok, I get it. Thank you so much.