QtScript 中变量影响的问题
我试图在 C++ 端获得脚本简单操作的结果。
我创建一个 QScriptValue (myvar) 并调用 engine.globalObject().setProperty("result", myvar);
然后我评估“result = anothervar + 7;”评估方法返回值正常,但变量结果不正常。 如果脚本是“result = anothervar + 7; a=1”,则结果值正常。
它看起来太愚蠢了,不可能是 Qt bug 那么我错过了什么?
谢谢杰夫
I'm trying to get the result of a script simple operation on the C++ side.
I create a QScriptValue (myvar) and call engine.globalObject().setProperty("result", myvar);
Then I evaluate "result = anothervar + 7;" The evaluate method return value is OK but the variable result is not OK.
If the script is "result = anothervar + 7; a=1" then the result value is OK.
It looks too stupid to be a Qt bug so what did I miss ?
Thanks
Jeff
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您对我的评论的回答,我假设您保留了
QScriptValue myvar
实例,并在调用evaluate()
后查看它:这将打印 2x " QVariant(double,21)”和一次“QVariant(double,1)”。这是预期的行为,原因如下:
在 JavaScript 中,一切都是对象,并且您只处理对对象的引用,而不是对象本身(如果您了解 Java,这类似于
int
与Integer
)。因此,赋值result = anotherVar + 7;
的作用是将myvar
表示的对象替换为全局对象的“result”属性,并使用表达式 < 产生的对象。代码>另一个Var + 7。同时,QScriptValuemyvar
仍然引用(旧)对象,否则此时该对象将被垃圾收集器抓取。关于添加
a=1
来解决问题:我无法在此处重现该问题。当然,第一个调试语句打印a
的值,但第二个和第三个没有改变。因此,问题的解决方案是在需要时始终从引擎重新获取“结果”属性(使用
engine.globalObject().property("result")
),或者——换句话说——QScriptValue 不跟踪分配。如果您确实想要跟踪分配,则需要将其转换为方法调用:将
result
实现为带有assign()
的自定义类方法,并将赋值 (=
) 替换为result.assign( anotherVal + 7 );
。From your answer to my comment, I'm assuming you're keeping the
QScriptValue myvar
instance around, and look at it after callingevaluate()
:This will print 2x "QVariant(double,21)" and once "QVariant(double,1)". That is expected behaviour, here's why:
In JavaScript, everything is an object, and you are only dealing with references to objects, not the objects themselves (if you know Java, this is similar to
int
vs.Integer
). So, what the assignmentresult = anotherVar + 7;
does is replace the object represented bymyvar
as the global object's "result" property with the object that results from the expressionanotherVar + 7
. Meanwhile, the QScriptValuemyvar
still references the (old) object, which otherwise would be up for grabs by the garbage-collecter at this point.About the addition of
a=1
to fix the problem: I can't reproduce that here. The first debug statement prints the value ofa
, of course, but the second and third are unchanged.The solution to your problem, therefore, is to always re-get the "result" property from the engine whenever you need it (using
engine.globalObject().property("result")
), or—in other words—QScriptValue doesn't track assigments.If you do want to track assignment, you need to turn it into a method call: Implement
result
as a custom class with anassign()
method, and replace assignment (=
) withresult.assign( anotherVal + 7 );
.