CopperSpice API  1.7.2
QScriptEngine Class Reference

The QScriptEngine class provides an environment for evaluating CsScript code. More...

Inheritance diagram for QScriptEngine:
QObject

Public Typedefs

typedef QScriptValue (* FunctionSignature) (QScriptContext *, QScriptEngine *)
 
typedef QScriptValue (* FunctionWithArgSignature) (QScriptContext *, QScriptEngine *, void *)
 

Public Types

enum  ValueOwnership
 

Public Signals

void signalHandlerException (const QScriptValue &exception)
 
- Public Signals inherited from QObject
void destroyed (QObject *obj=nullptr)
 
void objectNameChanged (const QString &objectName)
 

Public Methods

 QScriptEngine ()
 
 QScriptEngine (QObject *parent)
 
virtual ~QScriptEngine ()
 
void abortEvaluation (const QScriptValue &result=QScriptValue ())
 
QScriptEngineAgentagent () const
 
QStringList availableExtensions () const
 
bool canEvaluate (const QString &program) const
 
void clearExceptions ()
 
void collectGarbage ()
 
QScriptContextcurrentContext () const
 
QScriptValue defaultPrototype (int metaTypeId) const
 
QScriptValue evaluate (const QScriptProgram &program)
 
QScriptValue evaluate (const QString &program, const QString &fileName=QString (), int lineNumber=1)
 
template<typename T >
fromScriptValue (const QScriptValue &value)
 
QScriptValue globalObject () const
 
bool hasUncaughtException () const
 
QStringList importedExtensions () const
 
QScriptValue importExtension (const QString &extension)
 
void installTranslatorFunctions (const QScriptValue &object=QScriptValue ())
 
bool isEvaluating () const
 
QScriptValue newArray (uint length=0)
 
QScriptValue newDate (const QDateTime &value)
 
QScriptValue newDate (qsreal value)
 
QScriptValue newFunction (FunctionSignature signature, const QScriptValue &prototype, int length=0)
 
QScriptValue newFunction (FunctionSignature signature, int length=0)
 
QScriptValue newObject ()
 
QScriptValue newObject (QScriptClass *scriptClass, const QScriptValue &data=QScriptValue ())
 
QScriptValue newQMetaObject (const QMetaObject *metaObject, const QScriptValue &ctor=QScriptValue ())
 
QScriptValue newQObject (const QScriptValue &scriptObject, QObject *qtObject, ValueOwnership ownership=QtOwnership, const QObjectWrapOptions &options=Qt::EmptyFlag)
 
QScriptValue newQObject (QObject *object, ValueOwnership ownership=QtOwnership, const QObjectWrapOptions &options=Qt::EmptyFlag)
 
QScriptValue newRegExp (const QRegularExpression &regexp)
 
QScriptValue newRegExp (const QString &pattern, const QString &flags)
 
QScriptValue newVariant (const QScriptValue &object, const QVariant &value)
 
QScriptValue newVariant (const QVariant &value)
 
QScriptValue nullValue ()
 
void popContext ()
 
int processEventsInterval () const
 
QScriptContextpushContext ()
 
void reportAdditionalMemoryCost (int size)
 
template<class T >
QScriptValue scriptValueFromQMetaObject ()
 
void setAgent (QScriptEngineAgent *agent)
 
void setDefaultPrototype (int metaTypeId, const QScriptValue &prototype)
 
void setGlobalObject (const QScriptValue &object)
 
void setProcessEventsInterval (int interval)
 
QScriptValue toObject (const QScriptValue &value)
 
template<typename T >
QScriptValue toScriptValue (const T &value)
 
QScriptString toStringHandle (const QString &str)
 
QScriptValue uncaughtException () const
 
QStringList uncaughtExceptionBacktrace () const
 
int uncaughtExceptionLineNumber () const
 
QScriptValue undefinedValue ()
 
- Public Methods inherited from QObject
 QObject (QObject *parent=nullptr)
 
 ~QObject ()
 
bool blockSignals (bool block)
 
const QList< QObject * > & children () const
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool disconnect (const QObject *receiver, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod, const QString &location, const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod=QString (), const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
void dumpObjectInfo ()
 
void dumpObjectTree ()
 
QList< QStringdynamicPropertyNames () const
 
virtual bool event (QEvent *event)
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 
template<typename T >
findChild (const QString &childName=QString ()) const
 
template<class T >
QList< T > findChildren (const QRegularExpression &regExp, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
template<class T >
QList< T > findChildren (const QString &objName=QString (), Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
bool inherits (const QString &className) const
 
void installEventFilter (QObject *filterObj)
 
bool isWidgetType () const
 
bool isWindowType () const
 
void killTimer (int id)
 
const QMetaObjectmetaObject () const
 
void moveToThread (QThread *targetThread)
 
QString objectName () const
 
QObject * parent () const
 
template<class T = QVariant>
property (const QString &name) const
 
void removeEventFilter (QObject *obj)
 
void setObjectName (const QString &name)
 
void setParent (QObject *parent)
 
bool setProperty (const QString &name, const QVariant &value)
 
bool signalsBlocked () const
 
int startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer)
 
QThreadthread () const
 

Static Public Methods

static QScriptSyntaxCheckResult checkSyntax (const QString &program)
 
- Static Public Methods inherited from QObject
static bool connect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool connect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection, const QString &location=QString ())
 
static bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...), Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotLambda, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...))
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, std::nullptr_t slotMethod=nullptr)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotMethod)
 
static QMetaObjectstaticMetaObject ()
 
static QString tr (const char *text, const char *comment=nullptr, std::optional< int > numArg=std::optional< int >())
 

Additional Inherited Members

- Public Slots inherited from QObject
void deleteLater ()
 
- Protected Methods inherited from QObject
virtual void childEvent (QChildEvent *event)
 
virtual void connectNotify (const QMetaMethod &signalMethod) const
 
virtual void customEvent (QEvent *event)
 
virtual void disconnectNotify (const QMetaMethod &signalMethod) const
 
bool isSignalConnected (const QMetaMethod &signalMethod) const
 
int receivers (const QString &signal) const
 
QObject * sender () const
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *event)
 
- Properties inherited from QObject
 objectName
 

Detailed Description

The QScriptEngine class provides an environment for evaluating CsScript code.

See the CsScript documentation for information about the CsScript language and how to get started with scripting your application.

Evaluating Scripts

Use evaluate() to evaluate script code. This is the equivalent of the built-in script function eval().

QScriptEngine myEngine;
QScriptValue three = myEngine.evaluate("1 + 2");

evaluate() returns a QScriptValue which contains the result of the evaluation. The QScriptValue class provides functions for converting the result to various types (e.g. QScriptValue::toString() and QScriptValue::toNumber()).

The following code snippet shows how a script function can be defined and then invoked using QScriptValue::call():

QScriptValue fun = myEngine.evaluate("(function(a, b) { return a + b; })");
QScriptValueList args;
args << 1 << 2;
QScriptValue threeAgain = fun.call(QScriptValue(), args);

As can be seen from the above snippets, a script is provided to the engine in the form of a string. One common way of loading scripts is by reading the contents of a file and passing it to evaluate():

QString fileName = "helloworld.qs";
QFile scriptFile(fileName);
if (! scriptFile.open(QIODevice::ReadOnly))
// handle error
QTextStream stream(&scriptFile);
QString contents = stream.readAll();
scriptFile.close();
myEngine.evaluate(contents, fileName);

Here we pass the name of the file as the second argument to evaluate(). This does not affect evaluation in any way; the second argument is a general-purpose string that is used to identify the script for debugging purposes (for example, our filename will now show up in any uncaughtExceptionBacktrace() involving the script).

Engine Configuration

The globalObject() function returns the Global Object associated with the script engine. Properties of the Global Object are accessible from any script code (i.e. they are global variables). Typically, before evaluating "user" scripts, you will want to configure a script engine by adding one or more properties to the Global Object:

myEngine.globalObject().setProperty("myNumber", 123);
...
QScriptValue myNumberPlusOne = myEngine.evaluate("myNumber + 1");

Adding custom properties to the scripting environment is one of the standard means of providing a scripting API that is specific to your application. Usually these custom properties are objects created by the newQObject() or newObject() functions, or constructor functions created by newFunction().

Script Exceptions

evaluate() can throw a script exception (e.g. due to a syntax error); in that case, the return value is the value that was thrown (typically an Error object). You can check whether the evaluation caused an exception by calling hasUncaughtException(). In that case, you can call toString() on the error object to obtain an error message. The current uncaught exception is also available through uncaughtException(). Calling clearExceptions() will cause any uncaught exceptions to be cleared.

QScriptValue result = myEngine.evaluate(...);
if (myEngine.hasUncaughtException()) {
int line = myEngine.uncaughtExceptionLineNumber();
qDebug() << "uncaught exception at line" << line << ":" << result.toString();
}

The checkSyntax() function can be used to determine whether code can be usefully passed to evaluate().

Script Object Creation

Use newObject() to create a standard CsScript object. This is the equivalent of the script statement new Object(). You can use the object-specific functionality in QScriptValue to manipulate the script object (e.g. QScriptValue::setProperty()). Similarly, use newArray() to create a CsScript array object. Use newDate() to create a Date object, and newRegExp() to create a RegExp object.

QObject Integration

Use newQObject() to wrap a QObject (or subclass) pointer. newQObject() returns a proxy script object; properties, children, and signals and slots of the QObject are available as properties of the proxy object. No binding code is needed because it is done dynamically using the CopperSpice meta object system.

QPushButton button;
QScriptValue scriptButton = myEngine.newQObject(&button);
myEngine.globalObject().setProperty("button", scriptButton);
myEngine.evaluate("button.checkable = true");
qDebug() << scriptButton.property("checkable").toBoolean();
scriptButton.property("show").call(); // call the show() slot

Use qScriptConnect() to connect a C++ signal to a script method. This is the CsScript equivalent of QObject::connect(). When a script method is invoked in response to a C++ signal, it can cause a script exception which ou can connect to the signalHandlerException() signal to catch the exception.

Use newQMetaObject() to wrap a QMetaObject. This provide a "script representation" of a QObject based class. newQMetaObject() returns a proxy script object; enum values of the class are available as properties of the proxy object. You can also specify a function that will be used to construct objects of the class (e.g. when the constructor is invoked from a script). For classes that have a "standard" CopperSpice constructor, CsScript can provide a default script constructor for you. Refer to scriptValueFromQMetaObject().

For more information about QObject integration refer to Making Applications Scriptable

Support for Custom C++ Types

Use newVariant() to wrap a QVariant. This can be used to store values of custom (non-QObject) C++ types that have been registered with the CopperSpice meta type system. To make such types scriptable, you typically associate a prototype (delegate) object with the C++ type by calling setDefaultPrototype(); the prototype object defines the scripting API for the C++ type. Unlike the QObject integration, there is no automatic binding possible here; i.e. you have to create the scripting API yourself, for example by using the QScriptable class.

Use fromScriptValue() to cast from a QScriptValue to another type, and toScriptValue() to create a QScriptValue from another value. You can specify how the conversion of C++ types is to be performed with qScriptRegisterMetaType() and qScriptRegisterSequenceMetaType(). By default, CsScript will use QVariant to store values of custom types.

Importing Extensions

Use importExtension() to import plugin-based extensions into the engine. Call availableExtensions() to obtain a list naming all the available extensions, and importedExtensions() to obtain a list naming only those extensions that have been imported.

Call pushContext() to open up a new variable scope, and popContext() to close the current scope. This is useful if you are implementing an extension that evaluates script code containing temporary variable definitions (e.g. var foo = 123;) that are safe to discard when evaluation has completed.

Native Functions

Use newFunction() to wrap native (C++) functions, including constructors for your own custom types, so that these can be invoked from script code. Such functions must have the signature QScriptEngine::FunctionSignature. You may then pass the function as argument to newFunction(). Here is an example of a function that returns the sum of its first two arguments:

QScriptValue myAdd(QScriptContext *context, QScriptEngine *engine)
{
QScriptValue a = context->argument(0);
QScriptValue b = context->argument(1);
return a.toNumber() + b.toNumber();
}

To expose this function to script code, you can set it as a property of the Global Object:

QScriptValue fun = myEngine.newFunction(myAdd);
myEngine.globalObject().setProperty("myAdd", fun);

Once this is done, script code can call your function in the exact same manner as a "normal" script function:

QScriptValue result = myEngine.evaluate("myAdd(myNumber, 1)");

Long-running Scripts

If you need to evaluate possibly long-running scripts from the main (GUI) thread, you should first call setProcessEventsInterval() to make sure that the GUI stays responsive. You can abort a currently running script by calling abortEvaluation(). You can determine whether an engine is currently running a script by calling isEvaluating().

Garbage Collection

CsScript objects may be garbage collected when they are no longer referenced. There is no guarantee as to when automatic garbage collection will take place.

The collectGarbage() function can be called to explicitly request garbage collection.

The reportAdditionalMemoryCost() function can be called to indicate that a CsScript object occupies memory that is not managed by the scripting environment. Reporting the additional cost makes it more likely that the garbage collector will be triggered. This can be useful, for example, when many custom, native CsScript objects are allocated.

Core Debugging/Tracing Facilities

You can be notified of events pertaining to script execution (e.g. script function calls and statement execution) through the QScriptEngineAgent interface; see the setAgent() function. This can be used to implement debugging and profiling of a QScriptEngine.

See also
QScriptValue, QScriptContext, QScriptEngineAgent

Member Typedef Documentation

QScriptEngine::FunctionSignature

The function signature QScriptValue f(QScriptContext *, QScriptEngine *).

A function with such a signature can be passed to QScriptEngine::newFunction() to wrap the function.

QScriptEngine::FunctionWithArgSignature

The function signature QScriptValue f(QScriptContext *, QScriptEngine *, void *).

A function with such a signature can be passed to QScriptEngine::newFunction() to wrap the function.

Member Enumeration Documentation

This enum specifies the ownership when wrapping a C++ value, e.g. by using newQObject().

ConstantValueDescription
QScriptEngine::QtOwnership0The standard CopperSpice ownership rules apply, i.e. the associated object will never be explicitly deleted by the script engine. This is the default. (QObject ownership is explained in Object Trees & Ownership.)
QScriptEngine::ScriptOwnership1The value is owned by the script environment. The associated data will be deleted when appropriate (i.e. after the garbage collector has discovered that there are no more live references to the value).
QScriptEngine::AutoOwnership2If the associated object has a parent, the CopperSpice ownership rules apply (QtOwnership), otherwise the object is owned by the script environment (ScriptOwnership).

Constructor & Destructor Documentation

QScriptEngine::QScriptEngine ( )

Constructs a QScriptEngine object.

The globalObject() is initialized to have properties as described in ECMA-262, Section 15.1.

QScriptEngine::QScriptEngine ( QObject parent)
explicit

Constructs a QScriptEngine object with the given parent.

The globalObject() is initialized to have properties as described in ECMA-262, Section 15.1.

QScriptEngine::~QScriptEngine ( )
virtual

Destroys this QScriptEngine.

Method Documentation

void QScriptEngine::abortEvaluation ( const QScriptValue result = QScriptValue())

Aborts any script evaluation currently taking place in this engine. The given result is passed back as the result of the evaluation (i.e. it is returned from the call to evaluate() being aborted).

If the engine is not evaluating a script (i.e. isEvaluating() returns false), this function does nothing.

Call this function if you need to abort a running script for some reason, e.g. when you have detected that the script has been running for several seconds without completing.

See also
evaluate(), isEvaluating(), setProcessEventsInterval()
QScriptEngineAgent * QScriptEngine::agent ( ) const

Returns the agent currently installed on this engine, or 0 if no agent is installed.

See also
setAgent()
QStringList QScriptEngine::availableExtensions ( ) const

Returns a list naming the available extensions that can be imported using the importExtension() function. This list includes extensions that have been imported.

See also
importExtension(), importedExtensions()
bool QScriptEngine::canEvaluate ( const QString program) const
deprecated
Deprecated:
Returns true if program can be evaluated; i.e. the code is sufficient to determine whether it appears to be a syntactically correct program, or contains a syntax error.

This function returns false if program is incomplete; i.e. the input is syntactically correct up to the point where the input is terminated.

Note that this function only does a static check of program; e.g. it does not check whether references to variables are valid, and so on.

A typical usage of canEvaluate() is to implement an interactive interpreter for CsScript. The user is repeatedly queried for individual lines of code; the lines are concatenated internally, and only when canEvaluate() returns true for the resulting program is it passed to evaluate().

The following are some examples to illustrate the behavior of canEvaluate(). (Note that all example inputs are assumed to have an explicit newline as their last character, since otherwise the CsScript parser would automatically insert a semi-colon character at the end of the input, and this could cause canEvaluate() to produce different results.)

Given the input

if (hello && world) {
print("hello world");
}

canEvaluate() will return true, since the program appears to be complete.

Given the input

if (hello &&

canEvaluate() will return false, since the if-statement is not complete, but is syntactically correct so far.

Given the input

0 = 0

canEvaluate() will return true, but evaluate() will throw a SyntaxError given the same input.

Given the input

./test.js

canEvaluate() will return true, even though the code is clearly not syntactically valid CsScript code. evaluate() will throw a SyntaxError when this code is evaluated.

Given the input

foo["bar"]

canEvaluate() will return true, but evaluate() will throw a ReferenceError if foo is not defined in the script environment.

See also
evaluate(), checkSyntax()
QScriptSyntaxCheckResult QScriptEngine::checkSyntax ( const QString program)
static

Checks the syntax of the given program. Returns a QScriptSyntaxCheckResult object that contains the result of the check.

void QScriptEngine::clearExceptions ( )

Clears any uncaught exceptions in this engine.

See also
hasUncaughtException()
void QScriptEngine::collectGarbage ( )

Runs the garbage collector.

The garbage collector will attempt to reclaim memory by locating and disposing of objects that are no longer reachable in the script environment.

Normally you do not need to call this function; the garbage collector will automatically be invoked when the QScriptEngine decides that it's wise to do so (i.e. when a certain number of new objects have been created). However, you can call this function to explicitly request that garbage collection should be performed as soon as possible.

See also
reportAdditionalMemoryCost()
QScriptContext * QScriptEngine::currentContext ( ) const

Returns the current context.

The current context is typically accessed to retrieve the arguments and ‘this’ object in native functions; for convenience, it is available as the first argument in QScriptEngine::FunctionSignature.

QScriptValue QScriptEngine::defaultPrototype ( int  metaTypeId) const

Returns the default prototype associated with the given metaTypeId, or an invalid QScriptValue if no default prototype has been set.

See also
setDefaultPrototype()
QScriptValue QScriptEngine::evaluate ( const QScriptProgram program)

Evaluates the given program and returns the result of the evaluation.

QScriptValue QScriptEngine::evaluate ( const QString program,
const QString fileName = QString(),
int  lineNumber = 1 
)

Evaluates program, using lineNumber as the base line number, and returns the result of the evaluation.

The script code will be evaluated in the current context.

The evaluation of program can cause an exception in the engine; in this case the return value will be the exception that was thrown (typically an Error object). You can call hasUncaughtException() to determine if an exception occurred in the last call to evaluate().

lineNumber is used to specify a starting line number for program; line number information reported by the engine that pertain to this evaluation (e.g. uncaughtExceptionLineNumber()) will be based on this argument. For example, if program consists of two lines of code, and the statement on the second line causes a script exception, uncaughtExceptionLineNumber() would return the given lineNumber plus one. When no starting line number is specified, line numbers will be 1-based.

fileName is used for error reporting. For example in error objects the file name is accessible through the "fileName" property if it's provided with this function.

See also
canEvaluate(), hasUncaughtException(), isEvaluating(), abortEvaluation()
template<typename T >
T QScriptEngine::fromScriptValue ( const QScriptValue value)
inline

Returns the given value converted to the template type T.

Note that T must be known to QMetaType.

Refer to Conversion from %CsScript to C++ for a description of the built-in type conversion provided by CsScript.

See also
toScriptValue(), qScriptRegisterMetaType()
QScriptValue QScriptEngine::globalObject ( ) const

Returns this engine's Global Object.

By default, the Global Object contains the built-in objects that are part of ECMA-262, such as Math, Date and String. Additionally, you can set properties of the Global Object to make your own extensions available to all script code. Non-local variables in script code will be created as properties of the Global Object, as well as local variables in global code.

See also
setGlobalObject()
bool QScriptEngine::hasUncaughtException ( ) const

Returns true if the last script evaluation resulted in an uncaught exception, otherwise returns false.

The exception state is cleared when evaluate() is called.

See also
uncaughtException(), uncaughtExceptionLineNumber()
QStringList QScriptEngine::importedExtensions ( ) const

Returns a list naming the extensions that have been imported using the importExtension() function.

See also
availableExtensions()
QScriptValue QScriptEngine::importExtension ( const QString extension)

Imports the given extension into this QScriptEngine. Returns undefinedValue() if the extension was successfully imported. You can call hasUncaughtException() to check if an error occurred; in that case, the return value is the value that was thrown by the exception (usually an Error object).

QScriptEngine ensures that a particular extension is only imported once; subsequent calls to importExtension() with the same extension name will do nothing and return undefinedValue().

See also
availableExtensions(), QScriptExtensionPlugin, Creating CsScript Extensions
void QScriptEngine::installTranslatorFunctions ( const QScriptValue object = QScriptValue())

Installs translator functions on the given object, or on the Global Object if no object is specified.

The relation between CsScript translator functions and C++ translator functions is described in the following table:

Script FunctionCorresponding C++ Function
qsTr() QObject::tr()
QT_TR_NOOP() QT_TR_NOOP()
qsTranslate() QCoreApplication::translate()
QT_TRANSLATE_NOOP() QT_TRANSLATE_NOOP()
qsTrId() qtTrId()
QT_TRID_NOOP() QT_TRID_NOOP()
See also
Internationalization
bool QScriptEngine::isEvaluating ( ) const

Returns true if this engine is currently evaluating a script, otherwise returns false.

See also
evaluate(), abortEvaluation()
QScriptValue QScriptEngine::newArray ( uint  length = 0)

Creates a CsScript object of class Array with the given length.

See also
newObject()
QScriptValue QScriptEngine::newDate ( const QDateTime value)

Creates a CsScript object of class Date from the given value.

See also
QScriptValue::toDateTime()
QScriptValue QScriptEngine::newDate ( qsreal  value)

Creates a CsScript object of class Date with the given value (the number of milliseconds since 01 January 1970, UTC).

QScriptValue QScriptEngine::newFunction ( FunctionSignature  functionSig,
const QScriptValue prototype,
int  length = 0 
)

Creates a constructor function from functionSig with the given length. The prototype property of the resulting function is set to be the given prototype. The constructor property of prototype is set to be the resulting function.

When a function is called as a constructor, the "this" object associated with the function call is the new object the function is expected to initialize. The prototype of this default constructed object will be the function's public prototype property. If you always want the function to behave as a constructor or if you need to create your own object rather than using the default "this" object, you should make sure the prototype of your object is set correctly. Either set it manually or wrap a custom type by registering the defaultPrototype() of that type.

{
if (context->calledAsConstructor()) {
// initialize the new object
context->thisObject().setProperty("bar", ...);
return engine->undefinedValue();
} else {
// called as a function and not a constructor
// create our own object and return it
QScriptValue object = engine->newObject();
object.setPrototype(context->callee().property("prototype"));
object.setProperty("baz", ...);
return object;
}
}
...
QScriptValue fooProto = engine->newObject();
fooProto.setProperty("whatever", ...);
engine->globalObject().setProperty("Foo", engine->newFunction(Foo, fooProto));

The following is sample code to wrap a custom type and provide a constructor for it.

class Bar { ... };
Q_DECLARE_METATYPE(Bar)
QScriptValue constructBar(QScriptContext *context, QScriptEngine *engine)
{
Bar bar;
// initialize from arguments in context, if desired
...
return engine->toScriptValue(bar);
}
class BarPrototype : public QObject, public QScriptable
{
// provide the scriptable interface of this type using slots and properties
...
};
...
// create and register the Bar prototype and constructor in the engine
BarPrototype *barPrototypeObject = new BarPrototype(...);
QScriptValue barProto = engine->newQObject(barPrototypeObject);
engine->setDefaultPrototype(qMetaTypeId<Bar>, barProto);
QScriptValue barCtor = engine->newFunction(constructBar, barProto);
engine->globalObject().setProperty("Bar", barCtor);
QScriptValue QScriptEngine::newFunction ( FunctionSignature  c,
int  length = 0 
)

Creates a QScriptValue that wraps a native (C++) function specified by the given functionSig. The functionSig must be a C++ free function with signature matching QScriptEngine::FunctionSignature.

The length is the number of arguments functionSig expects and this becomes the length property of the created QScriptValue. The length only gives an indication of the number of arguments the function expects. An actual invocation of a function can include any number of arguments. This can be checked by calling argumentCount() on the QScriptContext passed to your function.

A prototype property is automatically created for the resulting function object to provide for the possibility that the function will be used as a constructor.

By combining newFunction() and the property flags QScriptValue::PropertyGetter and QScriptValue::PropertySetter, you can create script object properties which behaves like normal properties in script code, but are in fact accessed through functions. This is analogous to how properties work in Property System.

static QScriptValue getOrSetMyProperty(QScriptContext *context, QScriptEngine *engine)
{
QScriptValue callee = context->callee();
if (context->argumentCount() == 1) {
callee.setProperty("value", context->argument(0));
}
return callee.property("value");
}
....
QScriptValue object = engine.newObject();
object.setProperty("somePropertyName", engine.newFunction(getOrSetMyProperty), QScriptValue::PropertyGetter | QScriptValue::PropertySetter);

When the property somePropertyName of the script object is subsequently accessed in script code, getOrSetMyProperty() will be invoked to handle the access. In this particular case we are storing the "real" value of somePropertyName as a property of the accessor function itself.

In the example shown above a single native function was used to handle both reads and writes to the property. The argument count is used to determine if we are handling a read or write.

Alternatively, you can also use two separate free functions and specify the QScriptValue::PropertyGetter or QScriptValue::PropertySetter.

QScriptValue object = engine.newObject();
object.setProperty("somePropertyName", engine.newFunction(getMyProperty), QScriptValue::PropertyGetter);
object.setProperty("somePropertyName", engine.newFunction(setMyProperty), QScriptValue::PropertySetter);
See also
QScriptValue::call()
QScriptValue QScriptEngine::newObject ( )

Creates a CsScript object of class Object. The prototype of the created object will be the Object prototype object.

See also
newArray(), QScriptValue::setProperty()
QScriptValue QScriptEngine::newObject ( QScriptClass scriptClass,
const QScriptValue data = QScriptValue() 
)

Creates a CsScript Object of the given class, scriptClass.

The prototype of the created object will be the Object prototype object.

data, if specified, is set as the internal data of the new object (using QScriptValue::setData()).

See also
QScriptValue::scriptClass(), reportAdditionalMemoryCost()
QScriptValue QScriptEngine::newQMetaObject ( const QMetaObject metaObject,
const QScriptValue ctor = QScriptValue() 
)

Creates a CsScript object that represents a QObject class, using the given metaObject and constructor ctor.

Enums of metaObject (declared with CS_ENUM) are available as properties of the created QScriptValue. When the class is called as a function, ctor will be called to create a new instance of the class.

Example:

QScriptValue mySpecialQObjectConstructor(QScriptContext *context,
QScriptEngine *engine)
{
QObject *parent = context->argument(0).toQObject();
QObject *object = new QObject(parent);
return engine->newQObject(object, QScriptEngine::ScriptOwnership);
}
...
QScriptValue ctor = engine.newFunction(mySpecialQObjectConstructor);
engine.globalObject().setProperty("QObject", metaObject);
QScriptValue result = engine.evaluate("new QObject()");
See also
newQObject(), scriptValueFromQMetaObject()
QScriptValue QScriptEngine::newQObject ( const QScriptValue scriptObject,
QObject qtObject,
ValueOwnership  ownership = QtOwnership,
const QObjectWrapOptions options = Qt::EmptyFlag 
)

Initializes the given scriptObject to hold the given qtObject, and returns the scriptObject.

This function enables you to "promote" a plain CsScript object (created by the newObject() function) to a QObject proxy, or to replace the QObject contained inside an object previously created by the newQObject() function.

The prototype() of the scriptObject will remain unchanged.

If scriptObject is not an object, this function behaves like the normal newQObject(), i.e. it creates a new script object and returns it.

This method is useful when you want to provide a script constructor for a QObject based class. If your constructor is invoked in a new expression (QScriptContext::isCalledAsConstructor() returns true), you can pass QScriptContext::thisObject() (the default constructed script object) to this function to initialize the new object.

See also
reportAdditionalMemoryCost()
QScriptValue QScriptEngine::newQObject ( QObject object,
ValueOwnership  ownership = QtOwnership,
const QObjectWrapOptions options = Qt::EmptyFlag 
)

Creates a CsScript object that wraps the given QObject object, using the given ownership. The given options control various aspects of the interaction with the resulting script object.

Signals and slots, properties and children of object are available as properties of the created QScriptValue. For more information, see the CsScript documentation.

If object is a null pointer, this function returns nullValue().

If a default prototype has been registered for the object's class (or its superclass, recursively), the prototype of the new script object will be set to be that default prototype.

If the given object is deleted outside of the CsScript control, any attempt to access the deleted QObject's members through the CsScript wrapper object (either by script code or C++) will result in a script exception.

See also
QScriptValue::toQObject(), reportAdditionalMemoryCost()
QScriptValue QScriptEngine::newRegExp ( const QRegularExpression regexp)

Creates a CsScript object of class QRegularExpression with the given regexp.

See also
QScriptValue::toRegExp()
QScriptValue QScriptEngine::newRegExp ( const QString pattern,
const QString flags 
)

Creates a CsScript object of class QRegularExpressionwith the given pattern and flags.

The legal flags are 'g' (global), 'i' (ignore case), and 'm' (multiline).

QScriptValue QScriptEngine::newVariant ( const QScriptValue object,
const QVariant value 
)

Initializes the given CsScript object to hold the given variant value, and returns the object.

This function enables you to "promote" a plain CsScript object (created by the newObject() function) to a variant, or to replace the variant contained inside an object previously created by the newVariant() function.

The prototype() of the object will remain unchanged.

If object is not an object, this function behaves like the normal newVariant(), i.e. it creates a new script object and returns it.

This function is useful when you want to provide a script constructor for a C++ type. If your constructor is invoked in a new expression (QScriptContext::isCalledAsConstructor() returns true), you can pass QScriptContext::thisObject() (the default constructed script object) to this function to initialize the new object.

See also
reportAdditionalMemoryCost()
QScriptValue QScriptEngine::newVariant ( const QVariant value)

Creates a CsScript object holding the given variant value.

If a default prototype has been registered with the meta type id of value, then the prototype of the created object will be that prototype, otherwise the prototype will be the Object prototype object.

See also
setDefaultPrototype(), QScriptValue::toVariant(), reportAdditionalMemoryCost()
QScriptValue QScriptEngine::nullValue ( )

Returns a QScriptValue of the primitive type Null.

See also
undefinedValue()
void QScriptEngine::popContext ( )

Pops the current execution context and restores the previous one. This function must be used in conjunction with pushContext().

See also
pushContext()
int QScriptEngine::processEventsInterval ( ) const

Returns the interval in milliseconds between calls to QCoreApplication::processEvents() while the interpreter is running.

See also
setProcessEventsInterval()
QScriptContext * QScriptEngine::pushContext ( )

Enters a new execution context and returns the associated QScriptContext object. Once you are done with the context, you should call popContext() to restore the old context. By default, the ‘this’ object of the new context is the Global Object. The context's callee() will be invalid.

This function is useful when you want to evaluate script code as if it were the body of a function. You can use the context's activationObject() to initialize local variables that will be available to scripts. Example:

QScriptContext *context = engine.pushContext();
context->activationObject().setProperty("myArg", 123);
engine.evaluate("var tmp = myArg + 42");
...

In the above example, the new variable "tmp" defined in the script will be local to the context; in other words, the script does not have any effect on the global environment.

Returns a nullptr in case of astack overflow.

See also
popContext()
void QScriptEngine::reportAdditionalMemoryCost ( int  size)

Reports an additional memory cost of the given size, measured in bytes, to the garbage collector.

This function can be called to indicate that a CsScript object has memory associated with it that is not managed by CsScript itself. Reporting the additional cost makes it more likely that the garbage collector will be triggered.

Note that if the additional memory is shared with objects outside the scripting environment, the cost should not be reported, since collecting the CsScript object would not cause the memory to be freed anyway.

Negative size values are ignored, i.e. this function can not be used to report that the additional memory has been deallocated.

See also
collectGarbage()
template<class T >
QScriptValue QScriptEngine::scriptValueFromQMetaObject ( )

Creates a QScriptValue that represents the CopperSpice class T.

This function is used in combination with one of the Q_SCRIPT_DECLARE_QMETAOBJECT() macro. Example:

Q_SCRIPT_DECLARE_QMETAOBJECT(QLineEdit, QWidget*)
...
QScriptValue lineEditClass = engine.scriptValueFromQMetaObject<QLineEdit>();
engine.globalObject().setProperty("QLineEdit", lineEditClass);
See also
QScriptEngine::newQMetaObject()
void QScriptEngine::setAgent ( QScriptEngineAgent agent)

Installs the given agent on this engine. The agent will be notified of various events pertaining to script execution. This is useful when you want to find out exactly what the engine is doing, e.g. when evaluate() is called. The agent interface is the basis of tools like debuggers and profilers.

The engine maintains ownership of the agent.

Calling this function will replace the existing agent, if any.

See also
agent()
void QScriptEngine::setDefaultPrototype ( int  metaTypeId,
const QScriptValue prototype 
)

Sets the default prototype of the C++ type identified by the given metaTypeId to prototype.

The default prototype provides a script interface for values of type metaTypeId when a value of that type is accessed from script code. Whenever the script engine (implicitly or explicitly) creates a QScriptValue from a value of type metaTypeId, the default prototype will be set as the QScriptValue's prototype.

The prototype object itself may be constructed using one of two principal techniques; the simplest is to subclass QScriptable, which enables you to define the scripting API of the type through QObject properties and slots. Another possibility is to create a script object by calling newObject(), and populate the object with the desired properties (e.g. native functions wrapped with newFunction()).

See also
defaultPrototype(), qScriptRegisterMetaType(), QScriptable
void QScriptEngine::setGlobalObject ( const QScriptValue object)

Sets this engine's Global Object to be the given object. If object is not a valid script object, this function does nothing.

When setting a custom global object, you may want to use QScriptValueIterator to copy the properties of the standard Global Object; alternatively, you can set the internal prototype of your custom object to be the original Global Object.

See also
globalObject()
void QScriptEngine::setProcessEventsInterval ( int  interval)

Sets the interval between calls to QCoreApplication::processEvents to interval milliseconds.

While the interpreter is running, all event processing is by default blocked. This means for instance that the gui will not be updated and timers will not be fired. To allow event processing during interpreter execution one can specify the processing interval to be a positive value, indicating the number of milliseconds between each time QCoreApplication::processEvents() is called.

The default value is -1, which disables event processing during interpreter execution.

You can use QCoreApplication::postEvent() to post an event that performs custom processing at the next interval. For example, you could keep track of the total running time of the script and call abortEvaluation() when you detect that the script has been running for a long time without completing.

See also
processEventsInterval()
void QScriptEngine::signalHandlerException ( const QScriptValue exception)
signal

This signal is emitted when a script function connected to a signal causes an exception.

See also
qScriptConnect()
QScriptValue QScriptEngine::toObject ( const QScriptValue value)

Converts the given value to an object, if such a conversion is possible, otherwise returns an invalid QScriptValue. The conversion is performed according to the following table:

Input TypeResult
UndefinedAn invalid QScriptValue.
NullAn invalid QScriptValue.
BooleanA new Boolean object whose internal value is set to the value of the boolean.
NumberA new Number object whose internal value is set to the value of the number.
StringA new String object whose internal value is set to the value of the string.
ObjectThe result is the object itself (no conversion).
See also
newObject()
template<typename T >
QScriptValue QScriptEngine::toScriptValue ( const T &  value)
inline

Creates a QScriptValue with the given value.

Note that the template type T must be known to QMetaType.

See Conversion from %CsScript to C++ for a description of the built-in type conversion provided by QtScript. By default, the types that are not specially handled by CsScript are represented as QVariants (e.g. the value is passed to newVariant()); you can change this behavior by installing your own type conversion functions with qScriptRegisterMetaType().

See also
fromScriptValue(), qScriptRegisterMetaType()
QScriptString QScriptEngine::toStringHandle ( const QString str)

Returns a handle that represents the given string, str.

QScriptString can be used to quickly look up properties, and compare property names, of script objects.

See also
QScriptValue::property()
QScriptValue QScriptEngine::uncaughtException ( ) const

Returns the current uncaught exception, or an invalid QScriptValue if there is no uncaught exception.

The exception value is typically an Error object; in that case, you can call toString() on the return value to obtain an error message.

See also
hasUncaughtException(), uncaughtExceptionLineNumber()
QStringList QScriptEngine::uncaughtExceptionBacktrace ( ) const

Returns a human-readable backtrace of the last uncaught exception.

It is in the form <function-name>()&lt;file-name>:<line-number>.

See also
uncaughtException()
int QScriptEngine::uncaughtExceptionLineNumber ( ) const

Returns the line number where the last uncaught exception occurred.

Line numbers are 1-based, unless a different base was specified as the second argument to evaluate().

See also
hasUncaughtException()
QScriptValue QScriptEngine::undefinedValue ( )

Returns a QScriptValue of the primitive type Undefined.

See also
nullValue()