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!

Qt Code:
  1. #include <QScriptEngine>
  2. #include <QCoreApplication>
  3. #include <QFile>
  4. #include <QDebug>
  5.  
  6. static QScriptValue toQScriptValue( const QVector<double>& val, QScriptEngine& engine )
  7. {
  8. QScriptValue result = engine.newArray( val.size() );
  9. for ( int idx = 0; idx < val.size(); idx++ ) {
  10. result.setProperty( idx, val[ idx ] );
  11. }
  12. return result;
  13. }
  14.  
  15. int main( int argc, char** argv )
  16. {
  17. QCoreApplication app( argc, argv );
  18.  
  19. // two arrays gr, rhob
  20. int size = 10;
  21. QVector<double> gr( size ), rhob( size );
  22. for ( int idx = 0; idx < size; idx++ ) {
  23. gr[ idx ] = 200. * qrand() / RAND_MAX;
  24. rhob[ idx ] = 2.2 + 0.6 * qrand() / RAND_MAX;
  25. }
  26.  
  27. QScriptEngine engine;
  28. engine.globalObject().setProperty( "gr", toQScriptValue( gr, engine ) );
  29. engine.globalObject().setProperty( "rhob", toQScriptValue( rhob, engine ) );
  30.  
  31. // script to calculate mVar, nVar
  32. QString scriptFileName( "func.js" );
  33. QFile scriptFile( scriptFileName );
  34. scriptFile.open( QIODevice::ReadOnly );
  35. QString contents = scriptFile.readAll();
  36. scriptFile.close();
  37.  
  38. // not working
  39. QScriptValue func = engine.evaluate( contents, scriptFileName );
  40. qDebug() << func.toString();
  41. qDebug() << func.property( "mVar" ).toString();
  42. qDebug() << func.property( "nVar" ).toString();
  43.  
  44. // not working either
  45. QScriptValue result = func.call();
  46. qDebug() << result.toString();
  47. qDebug() << result.property( "mVar" ).toString();
  48. qDebug() << result.property( "nVar" ).toString();
  49.  
  50. }
To copy to clipboard, switch view to plain text mode 

and following is func.js script
Qt Code:
  1. var mVar;
  2. var nVar;
  3.  
  4. function calcMN()
  5. {
  6. mVar = new Array( gr.length );
  7. nVar = new Array( gr.length );
  8. for ( var idx = 0; idx < gr.length; idx++ ) {
  9. mVar[ idx ] = Math.pow( gr[ idx ], 2 ) / Math.pow( rhob[ idx ], 4 );
  10. nVar[ idx ] = gr[ idx ] / rhob[ idx ];
  11. print( "m = ", mVar[ idx ], ", n = ", nVar[ idx ] );
  12. }
  13. }
To copy to clipboard, switch view to plain text mode