简体   繁体   中英

Script in Qt doesn't return the correct value

I am trying to use the script in the Qt, here is a very simple code.

QCoreApplication a(argc, argv);

double x;

cout<<"Please enter a number: ";
cin>>x;
QFile file("cube.js");
if(!file.open(QIODevice::ReadOnly))
    abort();

QTextStream in(&file);
in.setCodec("UTF-8");
QString script=in.readAll();
file.close();
QScriptEngine interpreter;
QScriptValue operand(&interpreter,x);
interpreter.globalObject().setProperty("x",operand);
QScriptValue result=interpreter.evaluate(script);
cout<<"The result is "<<result.data().toInt32()<<endl;

return a.exec();

The content of the cube.js is only one line:

return x*x*x;

I run this program, but it always returns the zero. Could someone tell me what's wrong about in it? The file content is correct read.

Best Regards,

You are calling return on the Javascript global level, which is not allowed. You can use QScriptEngine::hasUncaughtException and QScriptValue QScriptEngine::uncaughtException to determine errors in the javascript code.

Also, you are calling result.data() which is for storing internal data. So the script should be

x*x*x

And the printout:

cout<<"The result is "<<result.toInt32()<<endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM