Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script in Qt doesn't return the correct value

Tags:

c++

qt

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,

like image 991
Yongwei Xing Avatar asked May 20 '11 07:05

Yongwei Xing


1 Answers

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;
like image 160
Tatu Lahtela Avatar answered Nov 05 '22 05:11

Tatu Lahtela