Yongwei Xing
Yongwei Xing

Reputation: 13441

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,

Upvotes: 5

Views: 185

Answers (1)

Tatu Lahtela
Tatu Lahtela

Reputation: 4554

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;

Upvotes: 6

Related Questions