![]() |
Home · Tutorial · Classes · Functions · Language · QSA Workbench · Qt Documentation · www.trolltech.com | ![]() |
Qt Script for Application's scripting language is called Qt Script, and it is an implementation of a subset of ECMAScript 4.0. ECMAScript is also called JavaScript or JScript by some vendors.
Qt Script provides the language features of ECMAScript, for example, while loops, class and function definitions, etc.
Qt Script also supports Trolltech's innovative signals and slots mechanism. Signals and slots provide type-safe inter-object communication that supercedes the crash-prone callbacks and message maps approaches used by older tools.
This language reference describes the language features provided by Qt Script. It is divided into the following chapters:
l{Qt Script Language Concepts} l{Built-in Types and Objects} l{Built-in Variables and Constants} l{Built-in Functions and Operators} l{Control Statements}
Readers are assumed to have a basic understanding of programming, and to have read the Getting Started with QSA guide that introduces Qt Script.
This chapter describes the concepts behind Qt Script, Qt Script for Application's implementation of ECMAScript.
Qt Script identifiers match the regex pattern [_A-Za-z][_A-Za-z0-9]*. Identifiers are used for variables, constants, class names, function names and labels.
ECMAScript reserves some words which are valid identifiers for its own use. See the Built-in Functions and Operators chapter for the complete list.
Variables are declared using the var keyword:
var a; // undefined var c = "foliage"; // the string "foliage" x = 1; // global variable
If a variable is assigned to without being declared, it is automatically declared as a global variable. Using global variables can make your code difficult to debug and maintain and is not recommended.
Constants are declared using the const keyword:
const x = "Willow"; const y = 42;
Constants must be defined at the point of declaration, because they cannot be changed later. If an attempt is made to assign to a constant, the Qt Script for Application interpreter will issue an error message and stop.
Constants are public globals if they are declared outside of any enclosing braces. When declared within the scope of some braces, e.g. within an if statment, their scope is local to the enclosing block.
Qt Script is a fully object oriented language. Classes can be defined as shown below in the source files of a project.
Example:
class Circle { var m_x; var m_y; var m_r; function Circle( posx, posy, radius ) { m_x = posx; m_y = posy; m_r = radius; } function setX( posx ) { m_x = posy; } function setY( posy ) { m_y = posy; } function setR( radius ) { m_r = radius; } function x() { return m_x; } function y() { return m_y; } function r() { return m_r; } } class ColorCircle extends Circle { var m_rgb; function ColorCircle( posx, posy, radius, rgbcolor) { Circle( posx, posy, radius ); m_rgb = rgbcolor; } function setRgb( rgbcolor ) { m_rgb = rgbcolor; } function rgb() { return m_rgb; } }
A class's constructor is the function which has the same (case-sensitive) name as the class itself. The constructor should not contain an explicit return statement; it will return an object of its type automatically. Qt Script does not have a destructor function (a function that is called when the class is destroyed), for a class.
The class's member variables are declared with var, and its member functions (methods) with function.
The object instance itself is referred to using the this operator. Inside a member function of a class, member variables and member functions can be accessed with an explicit this (e.g. this.x = posx;). This is not required, but can sometimes help to increase visibility.
Qt Script supports single inheritance, and if a class inherits from another class, the superclass's constructor can be called with super().
See also class, function, Function type, function operator.
Qualified Names
When you declare an object of a particular type, the object itself becomes, in effect, a namespace. For example, in Qt Script for Application there is a function called Math.sin(). If you wanted to have a sin() function in your own class that would not be a problem, because objects of your class would call the function using the object.function() syntax. The period is used to distinguish the namespace a particular identifier belongs to.
For example, in a Qt Script for Application GUI application, every application object belongs to the Application object. This can lead to some rather lengthy code, for example Application.Dialog.ListBox.count. Such long names can often be shortened, for example, within a signal handler, e.g. this.ListBox.count. In practice, Qt Script for Application is intelligent enough to work out the fully qualified name, so the code you would actually write is simply ListBox.count. The only time that you need to qualify your names is when an unqualified name is ambiguous.
A property is an undeclared variable that can be written to and accessed if the class supports properties. The classes supporting properties are Object, the application objects and the classes provided by the object and wrapper factories.
var obj = new Object object.myProperty = 100;
The class Object does not define the variable myProperty, but since the class supports properties, we can define the variable with that name on the fly and use it later. Properties are associated with the object they are assigned to, so even though the object obj in the example above gets the property myProperty, it does not mean that other objects of type Object will have the myProperty property, unless explicitly stated.
Qt Script supports the same commenting syntax as C++. One line comments may appear on a line of their own, or after the statements on a line. Multi-line comments may appear anywhere.
// A one line comment. /* A multi-line comment. */
Qt Script provides a variety of types and built-in objects. The types covered in the following sections are built into the Qt Script interpreter.
The built-in types include Array, Boolean, Date, Function type Number, Object, Point, Rect, RegExp, Size, String, Color, Palette, ColorGroup, ByteArray, Font and Pixmap.
The built-in objects include Math and System.
These are in some sense, Qt Script's 'native' datatypes.
An Array is a datatype which contains a named list of items. The items can be any Qt Script object. Multi-dimensional arrays are achieved by setting array items to be arrays themselves.
Arrays can be extended dynamically simply by creating items at non-existent index positions. Items can also be added using push(), unshift() and splice(). Arrays can be concatenated together using concat(). Items can be extracted using pop(), shift() and slice(). Items can be deleted using splice(). Arrays can be turned into strings using join() or Array::toString(). Use reverse() to reverse the items in an array, and sort() to sort the items. The sort() function can be passed a comparison function for customized sort orders.
In general, operations that copy array items perform a deep copy on items that are Number or String objects, and a shallow copy on other objects.
Arrays can be constructed from array literals or using the new operator:
var mammals = [ "human", "dolphin", "elephant", "monkey" ]; var plants = new Array( "flower", "tree", "shrub" ); var things = []; for ( i = 0; i < mammals.length; i++ ) { things[i] = new Array( 2 ); things[i][0] = mammals[i]; things[i][1] = plants[i]; }
Arrays can be initialized with a size, but with all items undefined:
var a = new Array( 10 ); // 10 items
Array items are accessed via their names. Names can be either integers or strings.
Example:
var m2 = mammals[2]; mammals[2] = "gorilla"; var thing = things[2][1]
The first statement retrieves the value of the third item of the mammals array and assigns it to m2, which now contains "monkey". The second statement replaces the third item of the mammals array with the value "gorilla". The third statement retrieves the second item of the third item's array from the things array and assigns it to thing, which now contains "shrub".
As stated above, it is also possible to access the arrays using strings. These act as normal properties, and can be accessed either using the square bracked operator ([]) or by directly dereferencing the array object and specifying the property name (.name). These two accessor types can be mixed freely as seen below with the address and phoneNumber properties.
var names = []; names["first"] = "John"; names["last"] = "Doe"; var firstName = names["first"]; var lastName = names["last"]; names["address"] = "Somewhere street 2"; names.phoneNumber = "+0123456789"; var address = names.address; var phoneNumber = names["phoneNumber"];
var x = new Array( "a", "b", "c" );
var y = x.concat( [ "d", "e" ], [ 90, 100 ] );
// y == [ "a", "b", "c", "d", "e", 90, 100 ]
Concatenates the array with one or more other arrays in the order given, and returns a single array.
var x = new Array( "a", "b", "c" ); var y = x.join(); // y == "a,b,c" var z = x.join( " * " ); // y == "a * b * c"
Joins all the items of an array together, separated by commas, or by the specified optSeparator.
var x = new Array( "a", "b", "c" );
var y = x.pop(); // y == "c" x == [ "a", "b" ]
Pops (i.e. removes) the top-most (right-most) item off the array and returns it.
var x = new Array( "a", "b", "c" );
x.push( 121 ); // x == [ "a", "b", "c", 121 ]
Pushes (i.e. inserts) the given items onto the top (right) end of the array. The function returns the new length of the array.
var x = new Array( "a", "b", "c", "d" );
x.reverse(); // x == [ "d", "c", "b", "a" ]
Reverses the items in the array.
var x = new Array( "a", "b", "c" );
var y = x.shift(); // y == "a" x == [ "b", "c" ]
Shifts (i.e. removes) the bottom-most (left-most) item off the array and returns it.
var x = new Array( "a", "b", "c", "d" ); var y = x.slice( 1, 3 ); // y == [ "b", "c" ] var z = x.slice( 2 ); // z == [ "c", "d" ]
Copies a slice of the array from the item with the given starting index, startIndex, to the item before the item with the given ending index, optEndIndex. If no ending index is given, all items from the starting index onward are sliced.
var x = new Array( "d", "x", "a", "c" );
x.sort(); // x == [ "a", "c", "d", "x" ]
Sorts the items in the array using string comparison. For customized sorting, pass the sort() function a comparison function, optComparisonFunction, that has the following signature and behavior:
function comparisonFunction( a, b ) // signature
The function must return an integer as follows:
Example:
function numerically( a, b ) { return a < b ? -1 : a > b ? 1 : 0; }
var x = new Array( 8, 90, 1, 4, 843, 221 );
x.sort( numerically ); // x == [ 1, 4, 8, 90, 221, 843 ]
var x = new Array( "a", "b", "c", "d" ); // 2nd argument 0, plus new items ==> insertion x.splice( 1, 0, "X", "Y" ); // x == [ "a", "X", "Y", "b", "c", "d" ] // 2nd argument > 0, and no items ==> deletion x.splice( 2, 1 ); // x == [ "a", "X", "b", "c", "d" ] // 2nd argument > 0, plus new items ==> replacement x.splice( 3, 2, "Z" ); // x == [ "a", "X", "b", "Z" ]
Splices items into the array and out of the array. The first argument, startIndex, is the start index. The second argument, replacementCount, is the number of items that are to be replaced. Make the second argument 0 if you are simply inserting items. The remaining arguments are the items to be inserted. If you are simply deleting items, the second argument must be > 0 (i.e. the number of items to delete), and there must be no new items given.
var x = new Array( "a", "b", "c" ); var y = x.toString(); // y == "a,b,c" var z = x.join(); // y == "a,b,c"
Joins all the items of an array together, separated by commas. This function is used when the array is used in the context of a string concatenation or is used as a text value, e.g. for printing. Use join() if you want to use your own separator.
var x = new Array( "a", "b", "c" );
x.unshift( 121 ); // x == [ 121, "a", "b", "c" ]
Unshifts (i.e. inserts) the given items at the bottom (left) end of the array.
ECMAScript provides a Boolean data type. In general, creating objects of this type is not recommended since the behavior will probably not be what you would expect.
Instead, use the boolean constants true and false as required. Any expression can be evaluated in a boolean context, e.g. in an if statement. If the expression's value is 0, null, false, NaN, undefined or the empty string "", the expression is false; otherwise the expression is true.
Instances of the Date class are used to store and manipulate dates and times.
A variety of get functions are provided to obtain the date, time or relevant parts, for example, getDay(), getYear(), getHours(), getMilliseconds(), getMinutes(), getMonth(), getSeconds(), getTime().
A complementary set of functions are also provided, including setYear(), setHours(), setMilliseconds(), setMinutes(), setMonth(), setSeconds(), setTime().
The functions operate using local time.
Conversion between Date objects to and from strings are provided by parse() and Date::toString().
Elapsed time (in milliseconds) can be obtained by creating two dates, casting them to Number and subtracting one value from the other.
var date1 = new Date();
// time flies..
var date2 = new Date();
var timedifference = date2.getTime() - date1.getTime();
var d = new Date( Date.parse( "1976-01-25T22:30:00" ) ); d = Date.parse( "1976-01-25T22:30:00" );
This is a static function that parses a string, dateString, which represents a particular date and time. It returns the number of milliseconds since midnight on the 1st January 1970. The string must be in the ISO 8601 extended format: YYYY-MM-DD or with time YYYY-MM-DDTHH:MM:SS.
Date() Date( milliseconds ) Date( year, month, day, optHour, optMinutes, optSeconds, optMilliseconds )
var today = new Date(); var d = new Date( 1234567 ); var date = new Date( 1994, 4, 21 ); var moment = new Date( 1968, 5, 11, 23, 55, 30 );
Dates can be constructed with no arguments, in which case the value is the date and time at the moment of construction using local time. A single integer argument is taken as the number of milliseconds since midnight on the 1st January 1970.
var d = new Date( 1975, 12, 25 );
var x = d.getDate(); // x == 25
Returns the day of the month using local time. The value is always in the range 1..31.
var d = new Date( 1975, 12, 25, 22, 30, 15 );
var x = d.getDay(); // x == 4
Returns the day of the week using local time. The value is always in the range 1..7, with the week considered to begin on Monday.
Example:
var IndexToDay = [ "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" ];
var d = new Date( 1975, 12, 28 );
System.println( IndexToDay[ d.getDay() - 1 ] ); // Prints "Sun"
var d = new Date( 1975, 12, 25 );
var x = d.getYear(); // x == 1975
Returns the year using local time.
var d = new Date( 1975, 12, 25, 22 );
var x = d.getHours(); // x == 22
Returns the hour using local time. The value is always in the range 0..23.
var d = new Date( 1975, 12, 25, 22 );
var x = d.getMilliseconds(); // x == 0
Returns the milliseconds component of the date using local time. The value is always in the range 0..999. In the example, x is 0, because no milliseconds were specified, and the default for unspecified components of the time is 0.
var d = new Date( 1975, 12, 25, 22, 30 );
var x = d.getMinutes(); // x == 30
Returns the minutes component of the date using local time. The value is always in the range 0..59.
var d = new Date( 1975, 12, 25, 22, 30 );
var x = d.getMonth(); // x == 12
Returns the months component of the date using local time. The value is always in the range 1..12.
Example:
var IndexToMonth = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
var d = new Date( 1975, 12, 25 );
System.println( IndexToMonth[ d.getMonth() - 1] ); // Prints "Dec"
var d = new Date( 1975, 12, 25, 22, 30 );
var x = d.getSeconds(); // x == 0
Returns the seconds component of the date using local time. The value is always in the range 0..59. In the example x is 0 because no seconds were specified, and the default for unspecified components of the time is 0.
var d = new Date( 1975, 12, 25, 22, 30 );
var x = d.getTime(); // x == 1.91457e+11
Returns the number of milliseconds since midnight on the 1st January 1970 using local time.
var d = new Date( 1975, 12, 25, 22, 30 );
d.setDate( 30 ); // d == 1975-12-30T22:30:00
Sets the day of the month to the specified dayOfTheMonth in local time.
var d = new Date( 1975, 12, 25, 22, 30 );
d.setYear( 1980 ); // d == 1980-12-30T22:30:00
Sets the year to the specified year in local time.
var d = new Date( 1975, 12, 25, 22, 30 );
d.setHours( 10 ); // d == 1980-12-30T10:30:00
Sets the hour to the specified hour, which must be in the range 0..23, in local time. The minutes, seconds and milliseconds past the hour (optMinutes, optSeconds and optMilliseconds) can also be specified.
var d = new Date( 1975, 12, 25, 22, 30 );
d.setMilliseconds( 998 ); // d == 1980-12-30T10:30:00:998
Sets the milliseconds component of the date to the specified value in local time.
var d = new Date( 1975, 12, 25, 22, 30 );
d.setMinutes( 15 ); // d == 1980-12-30T10:15:00
Sets the minutes to the specified minutes, which must be in the range 0..59, in local time. The seconds and milliseconds past the minute (optSeconds and optMilliseconds) can also be specified.
var d = new Date( 1975, 12, 25, 22, 30 );
d.setMonth(0); // d == 1980-01-11T22:30:00
Sets the month to the specified month, which must be in the range 0..11, in local time.
setSeconds( seconds )
var d = new Date( 1975, 12, 25, 22, 30 );
d.setSeconds( 25 ); // d == 1980-12-30T22:30:25
Sets the seconds to the specified seconds, which must be in the range 0..59, in local time.
var d = new Date( 1975, 12, 25, 22, 30 ); var duplicate = new Date(); duplicate.setTime( d.getTime() );
Sets the date and time to the local date and time given in terms of milliseconds since midnight on the 1st January 1970.
var d = new Date( 1975, 12, 25, 22, 30 );
var s = d.toString(); // s == "1975-12-25T22:30:00"
Converts the date into a string on the ISO 8601 extended format: YYYY-MM-DDTHH:MM:SS.
Functions are normally defined in the application's source code. In some situations it is desirable to create functions at run time.
var min = new Function( "x", "y", "return x < y ? x : y;" );
var m = min( 68, 9 ); // m == 9
The first arguments are the names of the parameters; the last argument is a string which contains the function's definition. It is also possible to supply the list of argument names as one comma separated string.
var min = new Function( "x,y", "return x < y ? x : y;" );
Variable numbers of arguments are also supported, using the arguments array, for example:
max = new Function(
"var max = 0;"
+ "for ( var i = 0; i < arguments.length; i++ ) {"
+ " if ( arguments[ i ] > max ) max = arguments[ i ];"
+ "}"
+ "return max;"
);
System.println( max( 50, 16, 24, 99, 1, 97 ) ); // Prints 99
A Number is a datatype that represents a number. In most sittuations, programmers will use numeric literals like 3.142 directly in code. The Number datatype is useful for obtaining system limits, e.g. MIN_VALUE and MAX_VALUE, and for performing number to string conversions with toString()
Numbers are not normally constructed, but instead created by simple assignment, e.g.
var x = 3.142;
A numeric variable can hold a non-numeric value, in which case isNaN() returns true. The result of an arithmetic expression may exceed the maximum or minimum representable values in which case the value of the expression will be Infinity, and isFinite() will return false.
An Object is the base type for all Qt Script objects.
Object provides a toString() function which is usually overridden by subclasses.
The Point class provides an implementation of a two dimensional point.
The Point class provides three different constructors.
var point = new Point( 20, 30 ); var duplicate = new Point( point ); // 20, 30 var zero = new Point(); // 0, 0
var p = new Point( 100, 200 ); System.println( "Point is: " + p.x + ", " + p.y );
A Rect object represents a rectangle.
The rectangle class provides three constructors.
var rect = new Rect( 10, 20, 30, 40 ); // x=10, y=20, width=30, height=40 var duplicate = new Rect( rect ); // x=10, y=20, width=30, height=40 var empty = new Rect(); // x=0, y=0, width=0, height=0
var empty = new Rect(); empty.isNull(); // true; var square = new Rect( 10, 10, 10, 10 ); square.isNull(); // false;
Returns true if the rectangle has a width and height of 0.
var rect = new Rect( 10, 10, -10, -10 ); rect.isEmpty(); // true var rect = new Rect( 10, 10, 10, 10 ); rect.isEmpty(); // false
Returns true if the rectangle is empty, meaning that it has width and/or height that is negative.
new Rect( 0, 0, 100, 100 ).contains( new Rect( 10, 10, 10, 10 ) ); // true new rect( 10, 10, 10, 10 ).contains( new Rect( 0, 0, 100, 100 ) ); // false
Returns true if the rectangle contains the other rectangle.
The Size class represents a two dimensional size. The size is represented using width and height.
The Size class provides three construtors:
var size = new Size( 100, 200 ); // width = 100, height = 200 var duplicate = new Size( size ); // width = 100, height = 200 var empty = new Size(); // width = 0, height = 0
A RegExp is a regular expression matcher for strings.
Regular expressions can be created either by using the /expression/ syntax or by using the RegExp constructor as shown below. Note that when using the RegExp constructor, a string is passed, and all backslashes must be escaped using an extra backslash, i.e. \\d. Below are two ways to create regular expressions that matches the pattern "QUANTITY=471 # Order quantity" and gets the number 471.
var directRegex = /([A-Z]+)=(\d+)/;
var str = "QUANTITY=471 # Order quantity";
str.match(directRegex);
directRegex.capturedTexts[2]; // "471";
var indirectRegex = new RegExp( "([A-Z]+)=(\\d+)" );
A regular expression can be set to global either by setting the global property on a regexp object or by specifying a trailing g in the pattern.
var re = /mypattern/g; // Global by method #1 var re = /mypattern/; re.global = true // Global by method #2
var re = /mypattern/i; // Case-insensitive by method #1 var re = /mypattern/; re.ignoreCase = true; // Case-insensitive by method #2
var re = /\d+ cm/; // matches one or more digits followed by space then 'cm' re.search( "A meter is 100 cm long" ); // returns 11
Searches text for the pattern defined by the regular expression. The function returns the position in the text of the first match or -1 if no match is found.
re = /name: ([a-zA-Z ]+)/; re.search( "name: John Doe, age: 42" ); re.cap(0); // returns "name: John Doe" re.cap(1); // returns "John Doe" re.cap(2); // returns undefined, no more captures.
Returns the nth capture of the pattern in the previously matched text. The first captured string (cap(0) ) is the part of the string that matches the pattern itself, if there is a match. The following captured strings are the parts of the pattern enclosed by parenthesis. In the example above we try to capture ([a-zA-Z ]+), which captures a sequence of one or more letters and spaces after the name: part of the string.
re = /name: ([a-zA-Z ]+)/; re.search( "name: John Doe, age: 42" ); re.pos(0); // returns 0, position of "name: John Doe" re.pos(1); // returns 6, position of "John Doe" re.pos(2); // returns -1, no more captures
Returns the position of the nth captured text in the search string.
A String is a sequence of zero or more Unicode characters. Qt Script's String class uses the Qt QString class's functions and syntax.
Strings can be created and concatenated as follows.
var text = "this is a";
var another = new String( "text" );
var concat = text + " " + another; // concat == "this is a text"
var s = String.fromCharCode( 65, 66, 67, 68 );
System.println( s ); // prints "ABCD"
Returns a string made up of the characters with code code1, code2, etc, according to their Unicode character codes.
match( pattern : RegExp ) : String; Returns the matched pattern if this string matches the pattern defined by regexp. If the string doesn't match or regexp is not a valid regular expression, undefined is returned.
If pattern is a regular expression with global set, all occurances of pattern in the string will be replaced.
The fieldWidth parameter specifies the minimum amount of space that value is padded to. A positive fieldWidth will produce right-aligned text, whereas a negative fieldWidth will produce left-aligned text.
value is expressed in base base, which is 10 by default and must be between 2 and 36.
Argument value is formatted according to the format specified, which is 'g' by default and can be any of the following:
With 'e', 'E', and 'f', precision is the number of digits after the decimal point. With 'g' and 'G', precision is the maximum number of significant digits (trailing zeroes are omitted).
The Color class is used to represent colors. Instances of Color can be passed to C++ slots that take arguments of type QColor.
The Palette class contains color groups for each widget state. A palette consists of three color groups: active, disabled, and inactive. All widgets contain a palette, and all widgets in Qt use their palette to draw themselves. This makes the user interface easily configurable and easier to keep consistent.
The QColorGroup class contains a group of widget colors.
The ByteArray class is an array optimized for storing raw bytes. Instances of ByteArray can be passed to C++ slots that take arguments of type QByteArray.
The Font class represents a font. Instances of Font can be passed to C++ slots that take arguments of type QFont.
The Pixmap class can be used to represent images in QSA. Instances of Pixmap can be passed to C++ slots that take arguments of type QPixmap.
The Pixmap constructor can take a filename referring to an image that will then be loaded:
var background = new Pixmap( "background.png" );
The built-in Math object provides functions that include: abs(), acos() and cos(), asin() and sin(), atan(), atan2() and tan(), ceil(), floor() and round(), exp() and log(), max() and min(), pow() and sqrt(), random(), and round().
The built-in System object provides functions including: getenv(), setenv(), print() and println().
The Math object always exists in a Qt Script program. Use the Math object to access mathematical constants and functions, e.g.
var x, angle, y; with ( Math ) { x = PI * 2; angle = 1.3; y = x * sin( angle ); }
The Math object supports all the common mathematical functions, for example: abs(), acos() and cos(), asin() and sin(), atan(), atan2() and tan(), ceil(), floor() and round(), exp() and log(), max() and min(), pow() and sqrt(), random(), and round().
See also, + operator, ++ operator, - operator, -- operator, * operator, / operator, % operator, -= operator, += operator, *= operator, /= operator and %= operator.
All the Math properties are read-only constants.
Returns the absolute value of the given number. The equivalent of
x = x < 0 ? -x : x;
var x = -99; var y = 99; with ( Math ) { x = abs( x ); y = abs( y ); } if ( x == y ) System.println( "equal" );
Example:
function polar( x, y ) { return Math.atan2( y, x ); }
Example:
var x = 913.41; x = Math.ceil( x ); // x == 914 var y = -33.97; y = Math.ceil( y ); // y == -33
The System object always exists in a Qt Script program. Use the System object to access and manipulate environment variables, e.g. with getenv() and setenv(), and to print text to the console with print() and println().
Example:
var q = System.getenv( "QTDIR" ); // q == "/usr/local/qt"
Qt Script for Application provides a number of convenient built-in constants and variables.
The built-in variables include arguments.
The built-in constants include Infinity, NaN and undefined.
This is an Array of the arguments that were passed to the function. It only exists within the context of a function.
Example:
function sum() { total = 0; for ( i = 0; i < arguments.length; i++ ) { total += arguments[ i ]; } return total; }
This is the value of any division by zero, i.e.
var i = 1/0;
In Qt Script, division by zero does not raise an exception; instead it assigns the Infinity value as the result of the expression. Use isFinite() to test whether a value is finite or not.
Some functions that are supposed to return a numeric result may return NaN instead. Use isNaN() to check for this.
This is the value of a variable that does not have a defined value, i.e. has not been assigned to.
Example:
var i;
// ...
if ( i == undefined ) {
i = 77;
}
In this example, if execution reaches the if statement, and i has not been assigned a value, it will be assigned the value 77.
Qt Script for Application provides many useful built-in functions and operators.
The built-in functions include connect(), debug(), eval(), isFinite(), isNaN(), killTimer(), killTimers(), parseFloat(), parseInt() and startTimer().
Classes, functions, variables and constants are declared with class, function, var and const respectively.
ECMAScript reserves the following words for future use:
boolean, byte, char, debugger, double, enum, export, float, goto, implements, import, int, interface, long, native, short, synchronized, throws, transient and volatile.
It is unadvisable to use any of these words as identifiers.
connect( signallingObject, signal, receivingObject, slot )
This function is used to create signals and slots connections between objects.
See the filter example program's example-script for an example.
connect( sender, signal, functionRef )
This function is used to create signals and slots connections between objects. functionRef can be a global function or a member of the class.
debug( expression )
Prints the expression (applying toString() if necessary) to the output (stderr), followed by a newline.
eval( string )
var x = 57;
var y = eval( "40 + x" ); // y == 97
This function parses and executes the contents of the string, taking the text to be valid Qt Script.
isFinite( expression )
Returns true if the expression's value is a number that is within range; otherwise returns false.
isNaN( expression )
Returns true if the expression's value is not a number; otherwise returns false.
Example:
var x = parseFloat( "3.142" );
var y = parseFloat( "haystack" );
if ( isNaN( x ) ) debug( "x is not a number" );
if ( isNaN( y ) ) debug( "y is not a number" );
// Prints: "y is not a number"
killTimer( timerId )
Stops and deletes the timer with the given timerId. Any events that are triggered by the timer with timerId will no longer be triggered.
See killTimers() and startTimer().
killTimers()
Stops and deletes all timers that have been created with startTimer(). Any events that are triggered by any of these timers will no longer be triggered.
See killTimer() and startTimer().
parseFloat( string )
Parses the string and returns the floating point number that the string represents or NaN if the parse fails. Leading and trailing whitespace are ignored. If the string contains a number followed by non-numeric characters, the value of the number is returned and the trailing characters ignored.
See also parseInt().
parseInt( string, optBase )
Parses the string and returns the integer that the string represents in the given base optBase, or NaN if the parse fails. If the base isn't specified, the base is determined as follows:
Leading and trailing whitespace are ignored. If the string contains a number followed by non-numeric characters, the value of the number is returned and the trailing characters ignored.
Example:
var i = parseInt( "24" ); // i == 24 var h = parseInt( "0xFF" ); // h == 255 var x = parseInt( " 459xyz " ); // x == 459
See also parseFloat().
var timerId = startTimer( interval, timeoutFunction )
Creates a new timer. The timer's id is returned, although it isn't needed if you use killTimers(). The timer calls the timeoutFunction every interval milliseconds.
The built-in operators include: + operator, ++ operator, - operator, -- operator, * operator, / operator, % operator, + string operator, += string operator, += operator, && operator, || operator, ! operator, & operator, ^ operator, | operator, ~ operator, << operator, >> operator, >>> operator, = operator, -= operator, *= operator, /= operator, %= operator, &= operator, ^= operator, |= operator, <<= operator, >>= operator, >>>= operator, == operator, != operator, === operator, !== operator, > operator, >= operator, ?: operator, , operator, function operator, in operator, instanceof operator, new operator, this operator and typeof operator.
These operators are used to assign the value of expressions to variables.
var variable = expression;
The assignment operator is used to assign the value of an expression to the variable.
It is an error to attempt to assign to a constant.
variable += expression;
This operator adds the value of the expression to the variable. It is the same as:
variable = variable + expression;
but is shorter to write, and less error-prone.
See also += string operator.
variable -= expression;
This operator subtracts the value of the expression from the variable.
variable *= expression;
This operator multiplies the value of the expression by the value of the variable.
variable /= expression;
This operator divides the value of the variable by the value of the expression.
variable %= expression;
This operator divides the variable by the expression, and assigns the remainder of the division (which may be 0), to the variable.
variable &= expression;
This operator performs a bit-wise AND on the value of the expression and the value of the variable, and assigns the result to the variable.
variable ^= expression;
This operator performs a bit-wise OR on the value of the expression and the value of the variable, and assigns the result to the variable.
variable |= expression;
This operator performs a bit-wise OR on the value of the expression and the value of the variable, and assigns the result to the variable.
variable <<= expression;
This operator performs a bit-wise left shift on the variable by an expression number of bits. Zeros are shifted in from the right.
variable >>= expression;
This operator performs a bit-wise (sign-preserving) right shift on the variable by an expression number of bits.
variable >>>= expression;
This operator performs a bit-wise (zero-padding) right shift on the variable by an expression number of bits.
These operators are used to perform arithmetic computations on their operands.
operand1 + operand2
This operator returns the result of adding the two operands (operand1 and operand2).
See also + string operator.
++operand; // pre-increment operand++; // post-increment
The pre-increment version of this operator increments the operand, and returns the value of the (now incremented) operand.
The post-incremented version of this operator returns the value of the operand, and then increments the operand.
var result = operand1 - operand2; // subtraction operand = -operand; // unary negation
The subtraction version of this operator returns the result of subtracting its second operand (operand2) from its first operand (operand1).
The unary negation version of this operator returns the result of negating (changing the sign) of its operand.
--operand; // pre-decrement operand--; // post-decrement
The pre-decrement version of this operator decrements the operand, and returns the value of the (now decremented) operand.
The post-decremented version of this operator returns the value of the operand, and then decrements the operand.
operand1 * operand2
This operator returns the result of multiplying the two operands (operand1 and operand2).
operand1 / operand2
This operator returns the result of dividing the first operand (operand1) by the second operand (operand2).
Note that division by zero is not an error. The result of division by zero is Infinity.
operand1 % operand2
This operator returns the integer remainder (which may be 0) from the division of operand1 by operand2.
These operators provide string functions using operators. Many other string functions are available, see String.
str1 + str2
This operator returns a string that is the concatenation of its operands, (str1 and str2).
See also + operator.
str1 += str2
This operator appends its second operand (str2) onto the end of the first operand (str1).
See also += operator.
These operators are used to evaluate whether their operands are true or false in terms of the operator (for unary operators) and in terms of each other (for binary operators).
The binary operators use short-circuit logic, i.e. they do not evaluate their second operand if the logical value of the expression can be determined by evaluating the first operand alone.
operand1 && operand2
This operator returns an object whose value is true if both its operands are true; otherwise it returns an object whose value is false.
Specifically, if the value of operand1 is false, the operator returns operand1 as its result. If operand1 is true, the operator returns operand2.
operand1 || operand2
This operator returns an object whose value is true if either of its operands are true; otherwise it returns an object whose value is false.
Specifically, if the value of operand1 is true, the operator returns operand1 as its result. If operand1 is false, the operator returns operand2.
! operand
If the operand's value is true, this operator returns false; otherwise it returns true.
These operators are used to compare objects and their values.
operand1 == operand2
Returns true if the operands are equal; otherwise returns false.
operand1 != operand2
Returns true if the operands are not equal; otherwise returns false.
operand1 === operand2
Returns true if the operands are equal and of the same type; otherwise returns false.
operand1 !== operand2
Returns true if the operands are not equal or if the operands are of different types; otherwise returns false.
operand1 > operand2
Returns true if operand1 is greater than operand2; otherwise returns false.
operand1 >= operand2
Returns true if operand1 is greater than or equal to operand2; otherwise returns false.
operand1 < operand2
Returns true if operand1 is less than operand2; otherwise returns false.
operand1 <= operand2
Returns true if operand1 is less than or equal to operand2; otherwise returns false.
operand1 & operand2
Returns the result of a bit-wise AND on the operands (operand1 and operand2).
operand1 ^ operand2
Returns the result of a bit-wise XOR on the operands (operand1 and operand2).
operand1 | operand2
Returns the result of a bit-wise OR on the operands (operand1 and operand2).
~ operand
Returns the bit-wise NOT of the operand.
operand1 << operand2
Returns the result of a bit-wise left shift of operand1 by the number of bits specified by operand2. Zeros are shifted in from the right.
operand1 >> operand2
Returns the result of a bit-wise (sign propagating) right shift of operand1 by the number of bits specified by operand2.
operand1 >>> operand2
Returns the result of a bit-wise (zero filling) right shift of operand1 by the number of bits specified by operand2. Zeros are shifted in from the left.
expression ? resultIfTrue : resultIfFalse
This operator evaluates its first operand, the expression. If the expression is true, the value of the second operand (resultIfTrue) is returned; otherwise the value of the third operand (resultIfFalse) is returned.
expression1, expression2
This operator evaluates its first and second operand (expression1 and expression2), and returns the value of the second operand (expression2).
The comma operator can be subtle, and is best reserved only for use in argument lists.
var variable = function( optArguments ) { Statements }
This operator is used to create anonymous functions. Once assigned, the variable is used like any other function name, e.g. variable(1, 2, 3). Specify the argument names (in optArguments) if named arguments are required. If no optArguments are specified, arguments may still be passed and will be available using the arguments list.
The Qt Script function operator supports closures, for example:
function make_counter( initialValue ) { var current = initialValue; return function( increment ) { current += increment; return current; } } // ... var counterA = make_counter( 3 ); // Start at 3. var counterB = make_counter( 12 ); // Start at 12. debug( counterA( 2 ) ); // Adds 2, so prints 5 debug( counterB( 2 ) ); // Adds 2, so prints 14 debug( counterA( 7 ) ); // Adds 7, so prints 12 debug( counterB( 30 ) ); // Adds 30, so prints 44
Note that for each call to make_counter(), the anonymous function that is returned has its own copy of current (initialized to the initialValue), which is incremented independently of any other anonymous function's current. It is this capturing of context that makes the function that is returned a closure.
See also function and Function type.
property in Object
Returns true if the given Object has the given property; otherwise returns false.
object instanceof type
Returns true if the given object is an instance of the given type, (or of one of its base classes); otherwise returns false.
var instance = new Type( optArguments );
This function calls the constructor for the given Type, passing it the optional arguments (optArguments) if any, and returns an instance of the given Type. The Type may be one of the built-in types, one of the library types, or a user-defined type.
Example:
var circle = new Circle( x, y ); var file = new File();
this.property
The this operator may only be used within a function that is defined within a class or form, i.e. a member function. Within the scope of the function this is a reference to the particular instance (object) of the class's type.
Example:
class MinMax { var _min; var _max; function MinMax( min, max ) { this._min = min; this._max = max; } function max() { return this._max; } function min() { return this._min; } function setMax( value ) { this._max = value; } function setMin( value ) { this._min = value; } }
typeof item
This operator returns a type of the object as a string.
Example:
var f = new Function("arguments[0]*2"); // "object" var str = "text"; // "string" var pi = Math.PI; // "number"
Classes, functions, variables and constants are declared with class, function, var and const respectively.
class ClassName {
static var ClassVariable;
var MemberVariable;
static function ClassFunction { Statements; }
function ClassName() { Statements; } // constructor
function MemberFunction() { Statements; }
}
This keyword is used to define new classes. After the keyword class comes the ClassName, then optionally, the keyword extends followed by a class name from which this class derives, then an opening brace. Class variables are declared with static var (ClassVariable). Only one instance of these variables exists per class. Member variables (MemberVariable), are declared with var; each instance (object) of the class has its own copy of each member variable. Functions declared with the keywords static function are class functions (ClassFunction); these functions are called using the name of the class rather than from an object. In the standard library, the Math functions are all static, for example Math.sin(). Member functions (methods) are called by objects and are declared with function. The constructor is the member function with the same name as the class; constructors must not contain an explicit return statement, or have an explicit return type, since Qt Script for Application handles these automatically.
A class that only contains static const, var and function definitions does not need a constructor.
Example:
class Area { static var count = 0; var _name; function Area( name ) { this._name = name; this.count++ } function destroy() { this.count--; } static function count() { return this.count; } function name() { return this._name; } function setName( name ) { this._name = name; } }
In this example we define the "Area" class. When an instance of the class is constructed:
var area = new Area( "Berkshire" );
the given name is assigned to the object's _name variable, and the class's static count is incremented. The destroy() function is not called automatically; it must be called explicitly if there is any clean-up to do.
All the class's variables and functions must be defined within the class definition. ECMAScript does not have destructors. But for Qt Script for Application forms, Qt Script for Application will call a class's destroy() function, if it has one, before deleting the form. This occurs because Qt Script for Application automatically connects the form's destroyed() signal to the destroy() function. If you want a destructor you must create your own and call it explicitly.
Classes are all derived from Object. It is possible to derive a class from another class using the extends keyword, for example:
class City extends Area { var _population; function City( name, population ) { Area( name ); _population = population; } function population() { return _population; } function setPopulation( population ) { _population = population; } }
See also function.
const identifier = Value;
This keyword is used to define constant values. The identifier is created as a constant with the given Value. The constant is global unless defined within the scope of a class or function.
Example:
const PI2 = Math.PI * 2; const COPYRIGHT = "Copyright (c) 2001";
Attempts to assign to a constant cause the interpreter to issue an error message and stop.
function functionName( arguments ) { Statements; }
Functions may also be declared within the scope of a class definition. In this situation, the functions become member functions (methods) of the class that contains them. See class.
var variableName; var anotherVariableName = InitialValue;
This keyword is used to declare and optionally initialize variables. If just the variableName is given, the variable is created, but it has no value, i.e. its value is undefined. If an InitialValue is given, the variable is created and assigned this InitialValue. Variables declared within functions are local to the function in which they are declared. Variables declared outside of functions and classes are global.
Example:
var i; var count = 22; var str = "string";
The flow--of--control in Qt Script programs is controlled by control statements, for example, if and switch, for and while. Qt Script also supports exceptions with try and catch.
label: for ( var i = 0; i < limit; i++ ) { if ( condition ) { break label; } } switch ( expression ) { case 1: Statements1; break; default: DefaultStatements; break; }
This keyword is used in for loops, do loops, while loops and switch statements. When a break statement is encountered in a loop, control is passed to the statement following the end of the inner-most loop that contains the break statement; unless the break statement is followed by the name of a label, in which case control passes to the statement governed by the label.
A break statement is usually placed at the end of each case in a switch statement to prevent the interpreter "falling through" to the next case. When the interpreter encounters a break statement, it passes control to the statement that follows the inner-most enclosing switch statement. If every case has a corresponding break, then at most one case's statements will be executed. If the break statement is followed by a label name (label) then when the break is encountered, control will pass to the statement marked with that label; this is useful, for example, for breaking out of deeply nested loops.
Example:
red: for ( x = 0; x < object.width; x++ ) { for ( y = 0; y < object.height; y++ ) { if ( color[x][y] == 0xFF0000 ) { break red; } } }
See switch for another example. See also do, while, for and break.
switch ( expression ) { case Value: Statements; break; default: DefaultStatements; break; }
This keyword is used in switch statements. For each possible value that a switch statement's expression may evaluate to, one case may be written, (but see default.) If a case's literal value (Value) matches the value of the switch statement's expression, then that case's statements (Statements) are executed.
Normally a case's statements are terminated by a break statement which causes execution to pass to the end of the switch statement.
See switch for an example.
try { Statements; } catch( exception ) { ExceptionStatements; }
This keyword is used in try statements. If an exception occurs, then the ExceptionStatements in a matching catch block are executed.
A catch block has the form:
catch ( e ) {
/* statements */
}
The possible exception types are:
EvalError -- the result of a failed eval() call. RangeError -- a result that is out of range, e.g. an array index to an element that isn't in the array. TypeError -- an attempt to perform an operation on an object of an inappropriate type. User defined exceptions -- exceptions that are objects of a user-defined type.
See try for an example.
for ( var i = 0; i < limit; i++ ) { if ( condition ) { continue; } Statements; }
This keyword is used within the context of a for, while or do loop.
If a continue statement is encountered in a for loop, execution immediately passes to the third part of the for loop (normally where a counter is incremented or decremented), and then execution continues normally, i.e. the middle part of the for loop (the conditional) is tested, and if true, the body of the loop is executed.
If a continue statement is encountered in a while or do loop, execution immediately passes to the conditional, which is retested; the body of the loop will be executed if the conditional is still true.
See do for an example. See also do, while, for and break.
switch ( expression ) { case 1 : Statements1; break; default : DefaultStatements; break; }
This keyword is used in switch statements. It is used instead of case to match anything that the switch statement's expression has evaluated to. If no default is used, and none of the cases match, then the switch statement will not execute anything and control will pass on to the following statement. If default is used, it must be the last case in the switch statement. This is because each case is evaluated in order, and since default matches any value, it will always be executed if the interpreter reaches it, and any following cases would always be ignored. When the default case is encountered its DefaultStatements are executed. It is customary to end a default statement with a break.
See switch for an example.
do { Statements; } while ( condition );
This keyword is used in conjunction with while to form a loop which is guaranteed to execute at least once.
The Statements in the braces following the do are executed once. If the while condition evaluates to true, execution passes back to the do, and the whole process repeats. If the while loop's conditional ever becomes false, execution continues from the statement following the while statement.
Example:
var x = 0; do { x += 5; if ( x == 50 ) continue; System.println( x ); } while ( x < 100 );
The example prints 5, 10, 15, ..., 45, 55, 60, 65, ..., 95 on the console.
See also while, for, continue and break.
if ( condition ) { Statements; } else { ElseStatements; }
The else keyword is used in conjunction with if. See if for details.
for ( i = 0; i < limit; i++ ) { Statements; }
This keyword is used to create a loop that executes a fixed number of times.
The for statement is broken into parts as follows: the keyword for, an opening parentheses, zero or more statements (the first part), a semi-colon, a conditional expression (the second part), a semi-colon, zero or more statements (the third part), a closing parentheses, and finally a statement or block that is governed by the for loop.
The first part of the for statement is typically used to initialize (and possibly declare) the variable used in the conditional in the second part of the for loop statement. This part is executed once before the loop begins. This part may be empty.
The second part contains a conditional expression. The expression is evaluated before each iteration of the loop (including before the first iteration). If this expression evaluates to false, the statement or block governed by the for loop is not executed and control passes to the statement that follows. If the condition is never true, the statement or block governed by the for loop will never be executed. If the condition expression is true, the statement or block governed by the for loop is executed, and then the third part of the for statement is executed, before control is passed back to the conditional expression with the whole process being repeated. This part should not be empty.
The third part contains statements which must be executed at the end of every iteration of the loop. This part is typically used to increment a variable that was initialized in the first part, and whose value is tested in the second part. This part may be empty.
Example:
var a = [ "a", "b", "c", "d", "e" ]; for( var i = 0; i < a.length; i++ ) { System.println( a[ i ] ); }
See also do, while, continue and break.
if ( expression1 ) { // statements1 else { // elsestatements } if ( expression1 ) { // statements1 else if ( expression2 ) { // statements2 } // else if ... else { // elsestatementsN }
An if statement provides a two-way branch. A multi-way branch is achieved using else ifs. (See also switch.)
If the first expression, expression1, is true, then the statements governed by that expression (statements1) will be executed, after which control will pass to the statement following the if block.
If expression1 is false, control passes to the else statement. If the else has no following if, the else statements (elsestatements) are executed, after which control will pass to the statement following the if block. If the else has a following if, then step 1 or step 2 (this step) is repeated for that if statement depending on whether its expression is true or false.
try { Statements; } finally { finalStatements; }
A finally block is a block of code that is executed after the governing try block. If no exceptions occur within the try block, control will pass to the finally block after the last statement in the try block has been executed. If an exception occurs within the try block, control is passed immediately to the finally block.
See also try.
labelname: Statement;
Statements may be labelled; the syntax is labelname followed by a colon, followed by the Statement. The labelname is any valid (unique) identifier.
See break for an example.
return optExpression;
A return statement may occur anywhere within a function, including member functions, but not within constructors. When a return statement is encountered, control leaves the function immediately, and execution resumes at the statement following the call that invoked the function. If the return statement is followed by an expression (optExpression) the value of the expression is returned to the caller.
Example:
function inRange( v, min, max ) { if ( v >= min && v <= max ) { return true; } else { return false; } }
switch( expression ) { case Value : Statements; break; default : DefaultStatements; break; }
A switch statement provides a multi-way branch. The expression is evaluated once, then each case is checked in order to find one with a Value that matches the value of the expression. If a match is made, the Statements of the matching case are executed, after which control passes to the statement following the switch block. If no matching case is found, and there is a default case, the DefaultStatements are executed, after which control passes to the statement following the switch block. If there is no matching case and no default, no statements within the switch block are executed, and control passes to the statement following the switch block.
Note that if a default is used it must be come after all the cases; this is because once default is encountered it is treated as a matching case regardless of what follows.
Every case, and the default (if used) should have a break as their last statement. If break is not present, control will "drop through" to the following statements, which is not usually the desired behavior.
The expression may be any arbitrary Qt Script for Application expression that evaluates to an object that can be strictly compared. For example, an expression that evaluates to a Boolean, Date, Number or String value.
Example:
switch( expr ) { case 1: doActionOne(); break; case "two": doActionTwo(); break; case 3: doActionThree(); case 4: doActionFour(); break; default: doDefaultAction(); break; }
In the example, if expr has the value 1, the doActionOne() function will be called. But if expr has the value 3, both doActionThree() and doActionFour() will be called, because case 3 doesn't have a break statement, and execution "falls through" to case 4. If expr is not 1, "two", 3 or 4 then the default case will be matched and doDefaultAction() will be executed.
See also break.
try { Statements; throw "an exception"; } catch ( e ) { if ( e == "an exception" ) { ExceptionStatements; } else { OtherExceptionStatements } }
The throw keyword is used to raise user-defined exceptions.
Example:
function monthToName( i ) { var IndexToMonth = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; if ( i < 0 || i > 11 ) { throw "month number out of range"; } else { return IndexToMonth[ i ]; } }
It is also possible to define a user-defined exception class and throw an object of that type, e.g.
throw new AUserDefinedException( "month number out of range" );
See also try.
try { Statements; } catch ( e ) { } try { Statements; } finally { }
The try keyword is used to identify a statement block for which exceptions will be caught. There are two kinds of try block, try...catch and try...finally.
try...catch
If an exception occurs within a try...catch block, control is passed to the first catch block. If that catch block does not accept the exception, control is passed on to the next catch block (if any), and so on, until there are no more catch blocks, in which case the exception is passed up the call chain until an enclosing catch block is found to accept it, or if none accept it, the program will terminate.
Catch blocks come in two varieties, unqualified and qualified. An unqualified catch block has the form:
catch ( e ) { /* statements */ }
and a qualified catch block has the form:
catch ( e if e instanceOf RangeError ) { /* statements */ }
See catch for details of the qualifiers.
try...finally
If an exception occurs within a try...catch block, control is passed to the finally block. This is useful if you want to ensure that something happens at the end of the block, no matter what.
Examples:
try { file = new File; file.open( filename ); process( file ); } finally { file.close(); }
In this example, the file is always closed, even if an exception occurred.
try { var a = monthToName( 11 ); var b = monthToName( 2 ); } catch ( e ) { if ( e == "month number out of range" ) { debug( "Code error: " + e ); } else { throw e; } }
In this example, the monthToName() function is called to set two variables. If the function fails, it throws an exception rather than returns an error value, so no explicit check for an error value is necessary. If one of the function calls failed debug() is called; otherwise the exception is re-thrown so that it can be handled at a higher level. (See throw for the definition of monthToName().)
while ( condition ) { Statements; }
This keyword is used to repeat a block of code zero or more times. When the while statement is encountered the condition is evaluated. If the condition is true, the Statements in the while block are executed; otherwise control passes to the statement following the while block. If the condition is true, after the Statements have been executed, the condition is again evaluated, and the whole process repeats.
Example:
var i = 10; while ( i > 0 ) { debug( i ); i--; }
See also do, for, continue and break.
with ( QualifyingName ) { Statements; }
This keyword is used to indicate that any unqualified names in the Statements should be qualified by QualifyingName. Please note that QSA does not allow declaration of variables using the 'var' statement inside a with block
Example:
// Without with System.print "one "; System.print "two "; System.println "three"; // With with with ( System ) { print "one "; print "two "; println "three"; }
If multiple qualifying names are required, with statements can be nested, e.g.
with ( System ) { with ( Math ) { print abs( -4 ); print pow( 2, 3 ); print random(); } }
Forcing the interpreter to do the lookup may be slower than using the fully qualified names.
Copyright © 2006 Trolltech | Trademarks | QSA 1.2.2 |