PDA

View Full Version : Can't get qScript to work



lni
18th September 2010, 14:49
Hi,

I have two arrays of QVector<double>, and I would like a script to calculate two variables mVar and nVar, I can't seem to get it to work.

Here is my C++ codes and the script, can anyone help please? Thanks!




#include <QScriptEngine>
#include <QCoreApplication>
#include <QFile>
#include <QDebug>

static QScriptValue toQScriptValue( const QVector<double>& val, QScriptEngine& engine )
{
QScriptValue result = engine.newArray( val.size() );
for ( int idx = 0; idx < val.size(); idx++ ) {
result.setProperty( idx, val[ idx ] );
}
return result;
}

int main( int argc, char** argv )
{
QCoreApplication app( argc, argv );

// two arrays gr, rhob
int size = 10;
QVector<double> gr( size ), rhob( size );
for ( int idx = 0; idx < size; idx++ ) {
gr[ idx ] = 200. * qrand() / RAND_MAX;
rhob[ idx ] = 2.2 + 0.6 * qrand() / RAND_MAX;
}

QScriptEngine engine;
engine.globalObject().setProperty( "gr", toQScriptValue( gr, engine ) );
engine.globalObject().setProperty( "rhob", toQScriptValue( rhob, engine ) );

// script to calculate mVar, nVar
QString scriptFileName( "func.js" );
QFile scriptFile( scriptFileName );
scriptFile.open( QIODevice::ReadOnly );
QString contents = scriptFile.readAll();
scriptFile.close();

// not working
QScriptValue func = engine.evaluate( contents, scriptFileName );
qDebug() << func.toString();
qDebug() << func.property( "mVar" ).toString();
qDebug() << func.property( "nVar" ).toString();

// not working either
QScriptValue result = func.call();
qDebug() << result.toString();
qDebug() << result.property( "mVar" ).toString();
qDebug() << result.property( "nVar" ).toString();

}


and following is func.js script



var mVar;
var nVar;

function calcMN()
{
mVar = new Array( gr.length );
nVar = new Array( gr.length );
for ( var idx = 0; idx < gr.length; idx++ ) {
mVar[ idx ] = Math.pow( gr[ idx ], 2 ) / Math.pow( rhob[ idx ], 4 );
nVar[ idx ] = gr[ idx ] / rhob[ idx ];
print( "m = ", mVar[ idx ], ", n = ", nVar[ idx ] );
}
}

wysota
18th September 2010, 21:49
At which point does the code fail? Does the rhob array in the script have proper values that were set in C++?