简体   繁体   English

Qt中的脚本未返回正确的值

[英]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. 我正在尝试在Qt中使用脚本,这是一个非常简单的代码。

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: cube.js的内容只有一行:

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. 您在Javascript全局级别调用return,这是不允许的。 You can use QScriptEngine::hasUncaughtException and QScriptValue QScriptEngine::uncaughtException to determine errors in the javascript code. 您可以使用QScriptEngine::hasUncaughtExceptionQScriptValue QScriptEngine::uncaughtException来确定JavaScript代码中的错误。

Also, you are calling result.data() which is for storing internal data. 另外,您正在调用result.data() ,用于存储内部数据。 So the script should be 所以脚本应该是

x*x*x

And the printout: 和打印输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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