I have a program using QtScript for some automation. I added a bunch of C ++ functions and classes to the global scope of the script engine so that scripts can access them, for example:
QScriptValue fun = engine->newFunction( systemFunc );
engine->globalObject().setProperty( "system", fun );
I would like to be able to run several scripts in a row, each of which has a new global state. Therefore, if one script sets a global variable, for example
myGlobalVar = "stuff";
I want this variable to be deleted before the next script run. My method for doing this is to make a deep copy of the global script engine object and then restore it when the script ends. But deep copies do not work, as my function systemsuddenly breaks with an error:
TypeError: Result of expression 'system' [[object Object]] is not a function.
Here is my deep copy function adapted from:
http://qt.gitorious.org/qt-labs/scxml/blobs/master/src/qscxml.cpp
QScriptValue copyObject( const QScriptValue& obj, QString level = "" )
{
if( obj.isObject() || obj.isArray() ) {
QScriptValue copy = obj.isArray() ? obj.engine()->newArray() : obj.engine()->newObject();
copy.setData( obj.data() );
QScriptValueIterator it(obj);
while(it.hasNext()) {
it.next();
qDebug() << "copying" + level + "." + it.name();
if( it.flags() & QScriptValue::SkipInEnumeration )
continue;
copy.setProperty( it.name(), copyObject(it.value(), level + "." + it.name()) );
}
return copy;
}
return obj;
}
( SkipInEnumerationwas introduced to avoid an infinite loop)
EDIT: I think part of the problem is that in the debugger (QScriptEngineDebugger) the functions and constructors that I added should be displayed as a type Function, but after copying they are displayed as a type Object. I have not yet found a good way to create a new function that duplicates an existing one (QScriptEngine :: newFunction accepts the actual function pointer).
source
share