PDA

View Full Version : How to use QScript?



lni
1st August 2010, 14:31
Hi,

I am looking at Qt's script example but got lost...

I have several QVector<double> array in my C++ program with same length, such as

QVector<double> aArray, bArray, cArray...

I want users to be able to enter their own math expression, such as:

result = aArray^2 + bArray / cArray.

The operation is actually on each element. In C++, it would look like this:

QVector<double> result( aArray.length() );
for ( int idx = 0; idx < aArray.length(); idx++ ) {
result [ idx ] = aArray[ idx ]^2 + bArray[ idx ] / cArray[ idx ].
}

Then the result should be returned to the C++ program.

Can someone give me a light?

Many thanks.

asvil
1st August 2010, 17:51
ECMA Script don't have operator overloading.
First way, use QScript like Cpp:


arrayA = [0.1, 0.4, 0.5]
arrayB = [0.1, 0.1, 0.7]
arrayC = [0.6, 0.23, 0.44]
for ( var idx = 0; idx < aArray.length; ++idx) {
result[idx] = aArray[idx]^2 + bArray[idx]/cArray[idx].
}

Second way create functions for array prototype:


Array.prototype.addition = function(other) {
var result;
for (var i; i < this.length; ++i) {
result[i] = this[i] + other[i];
}
return result;
}
Array.prototype.division = function(other) {
var result;
for (var i; i < this.length; ++i) {
result[i] = this[i]/other[i];
}
return result;
}
Array.prototype.power = function(number) {
var result;
for (var i; i < this.length; ++i) {
result[i] = Math.pow(this[i], other[i]);
}
return result;
}

Using


arrayA = [0.1, 0.4, 0.5]
arrayB = [0.1, 0.1, 0.7]
arrayC = [0.6, 0.23, 0.44]
result = (arrayA.power(2)).addition(bArray.division(cArray) );
//result[idx] = aArray[idx]^2 + bArray[idx]/cArray[idx]

borisbn
2nd August 2010, 04:19
And do not forget, that operator ^ is not a pow, but XOR :)

asvil
2nd August 2010, 06:23
Yes, it's xor operator)

lni
2nd August 2010, 14:14
But how to pass array from C++ to the script? The examples aArray, bArray, and cArray are created insider the script...

asvil
2nd August 2010, 14:36
The simplest way:
C++


QScriptValue makeQSArray(QVector<double> array, QScriptEngine* engine)
{
QScriptValue result = engine->newArray(array.count());
for (int i = 0; i < array.count(); ++i) {
result.setProperty(i, array.at(i));
}
return result;
}

............................
{
QVector<double> arrayA;
arrayA << 0.1 << 0.4;
engine->globalObject()->setProperty(arrayA, makeQSArray(arrayA, engine));
}
.........................

Now, property 'arrayA' of globalObject is array.