Project Editor User Guide
Project Editor User Guide
Ed.: 09/2017
© 2012 - 2017 Datalogic S.p.A. and/or its affiliates ALL RIGHTS RESERVED. Without
limiting the rights under copyright, no part of this documentation may be reproduced,
stored in or introduced into a retrieval system, or transmitted in any form or by any means,
or for any purpose, without the express written permission of Datalogic S.p.A. and/or its
affiliates. Datalogic and the Datalogic logo are registered trademarks of Datalogic S.p.A. in
many countries, including the U.S.A. and the E.U.
Lighter Suite is trademark of Datalogic S.p.A. and/or affiliates. All other trademarks and
brands are property of their respective owners.
Datalogic reserves the right to make modifications and improvements without prior
notification.
Datalogic shall not be liable for technical or editorial errors or omissions contained herein,
nor for incidental or consequential damages resulting from the use of this material.
Ed. 09/2017
ii
REVISION INDEX
09/2017 22/09/2017 ii
NOTE:
We sometimes update the documentation after original publication. Theref ore, you s hould also
review the documentation at www.datalogic.com for updates.
iii
TABLE OF CONTENTS
REVISION INDEX...........................................................................................................................iii
TABLE OF CONTENTS.................................................................................................................. iv
1. WELCOME............................................................................................................................. 6
1.1 ABOUT THIS HELP SYSTEM............................................................................................. 6
1.1.1 Using the Help System: .............................................................................................. 6
1.1.2 Contents of the Help: .................................................................................................. 6
3. MANAGING PROJECTS......................................................................................................... 11
3.1 EDITOR CONFIGURATION ............................................................................................. 12
3.2 CREATING A PROJECT.................................................................................................. 13
3.3 ADDING FILES TO THE PROJECT................................................................................... 15
3.3.1 Creating a new source file......................................................................................... 16
3.3.2 Importing source or resource f iles into a project ............................................................ 16
3.4 WORKING WITH SOURCE FILES .................................................................................... 17
3.4.1 Copying, cutting, and pasting text ............................................................................... 18
3.4.2 Searching or replacing text ........................................................................................ 19
3.4.3 Renaming or deleting f iles ......................................................................................... 20
3.4.4 Exporting source f iles ............................................................................................... 20
3.5 ABOUT FORMATTERS................................................................................................... 21
iv
6. LASER ENGINE LANGUAGE REFERENCE.............................................................................. 30
6.1 IDENTIFIERS AND RESERVED WORDS .......................................................................... 31
6.1.1 What are identifiers .................................................................................................. 31
6.1.2 Reserved words (Keywords)...................................................................................... 31
6.2 COMMENTING THE CODE ............................................................................................. 33
6.3 DECLARATIONS............................................................................................................ 34
6.3.1 Declaring Functions.................................................................................................. 34
6.3.2 Declaring Classes .................................................................................................... 34
6.3.3 Declaring Variables .................................................................................................. 35
6.3.4 Declaring Constants ................................................................................................. 36
6.4 CONTROL STATEMENTS............................................................................................... 37
6.4.1 Break ..................................................................................................................... 38
6.4.2 Const..................................................................................................................... 39
6.4.3 Continue................................................................................................................. 40
6.4.4 For ........................................................................................................................ 42
6.4.5 Function ................................................................................................................. 43
6.4.6 If...else ................................................................................................................... 44
6.4.7 Label ..................................................................................................................... 46
6.4.8 Return.................................................................................................................... 46
6.4.9 Switch.................................................................................................................... 47
6.4.10 Throw .................................................................................................................... 49
6.4.11 Try...catch............................................................................................................... 52
6.4.12 Var ........................................................................................................................ 54
6.4.13 While ..................................................................................................................... 55
6.4.14 With....................................................................................................................... 56
6.5 CLASSES AND METHODS (MEMBER FUNCTIONS) .......................................................... 58
6.5.1 Qualified Names ...................................................................................................... 58
6.5.2 Class Properties ...................................................................................................... 58
6.6 NATIVE AND BUILT-IN OBJECTS .................................................................................... 59
6.6.1 Native Objects ......................................................................................................... 59
6.6.2 Arguments variable .................................................................................................. 95
6.6.3 Built-in Constants..................................................................................................... 96
6.6.4 Built-in Functions ..................................................................................................... 97
6.6.5 Built-in Operators ....................................................................................................100
NOTE: .......................................................................................................................................107
v
PROJECT EDITOR
1
1. WELCOME
Chapter Contents
Presents an overview of the product in t erms of s cope and
Getting started with Project Editor
work environment.
Describes how to create a project, how to add source or
Managing Projects
resource f iles, as well as to manage files.
Describes how to open or save an existing project, either
Opening, Saving, and Deleting Projects
locally or to/from the laser device.
Describes how to test and run a project, and how to send it to
Sending projects to marking
marking.
Describes all of the objects, types, f unctions, variables,
Laser Engine Language Reference classes, and constants that can be used t o writ e y our own
programs.
6
GETTING STARTED WITH PROJECT EDITOR
2
7
PROJECT EDITOR
2
Such programs are then interpreted and executed via the Laser Engine. The programming language is an
implementation of a subset of ECMAScript 4.0. ECMAScript, which is also called JavaScript o r J Script by
some vendors.
Project Editor is launched by choosing File > Project Editor from the Laser Editor's menu bar.
Tip:
Ref erence material on the programming language is provided into the Laser Engine Lang uage
Ref erence section of this Help System. To access it, choose menu Help > Help or press F1 at a
window level.
Related topics:
• Work environment overview
• Managing Projects
8
GETTING STARTED WITH PROJECT EDITOR
2
The picture below shows the main window of Project Editor when you access it:
Tip:
To hide/unhide a pane in the Project Editor window, either use the Window menu or right-click in
a blank area next to the toolbar.
9
PROJECT EDITOR
2
Menu bar with all the Project Editor commands. All functions are described later.
Toolbar - It shows the tools that allow creating, managing and running the project . P oint and
hover a button to display a tooltip. All functions are described later.
Right-click this area to display a shortcut menu that allows you to hide/unhide t he p anes 5, 6,
and 7.
Project Files pane - It lists the source files and resource files that compose the current projec t.
Right-clicking an item (either the project folder, the source files folder, the resource files f older,
or a f ile) will result in a shortcut menu being displayed on which you can choose options for files
management.
This window can float over the work area, or you can dock it at the left-s ide of t he window b y
double-clicking its title bar. Furthermore, you can hide/display this window by right-clicking next
to the toolbar and then selecting/deselecting the corresponding option.
Program editor area - This is the area where the source file is displayed. You c an ent er y our
code, edit it, copy, paste or search the code by using the menus or the toolbar. To c ust omize
how the editor looks, choose Edit > Configuration and then enter the desired values.
Output area - When you run a project, it displays the relevant status or error messages.
This window can float over the work area, or you can dock it at t he b ottom of t he window by
double-clicking its title bar. Furthermore, you can hide/display this window by right-clicking next
to the toolbar and then selecting/deselecting the corresponding option.
10
MANAGING PROJECTS
3
3. MANAGING PROJECTS
11
PROJECT EDITOR
3
2. From the Element list, choose the item(s) you want to change the f ormatting f or and enter the
desired values.
3. When f inished, click OK.
Related topics:
• Creating a project
• Adding files to the project
12
MANAGING PROJECTS
3
When you are working on a project, the Project Files pane lists all the files that compose t he p roject. The
pane is displayed by default on the left side of the window.
• Right-click the Project folder to open a shortcut menu that shows a list of c ommands f or p rojec t
management (such as renaming or adding files):
13
PROJECT EDITOR
3
• Right-click any document or project file to open a shortcut menu that shows a lis t of commands
relevant to it.
• Move the pane to another location in the window by clicking the title bar. To rest ore t he original
position and dock the pane, double-click the title bar.
• Hide/unhide the pane by right-clicking in a blank area next to the toolbar, and then deselect /s elec t
the corresponding item.
Tip:
Ref erence material f or developers is provided into the Laser Engine Language
Ref erence section of this Help system.
Related topics:
• Adding files to the project
• Importing source or resource files into a project
14
MANAGING PROJECTS
3
(For f urther information, see Importing source or resource files into a project.)
Source and resource files that compose the project are listed into the Project Files pane, which is displayed
by default on the left side of the window.
All the f iles that compose the project, are then synchronized when the project is executed, that is , t hey are
copied to the device before being executed.
Files management commands are available by right-clicking the files folder or an ind ividual f ile and t hen
choosing an option form the shortcut menu. See pictures below:
Related topics:
• Creating a new source file
• Importing source or resource files into a project
• Working with Source files
15
PROJECT EDITOR
3
2. In the Input file name window that is displayed, enter the name for the source file and click OK.
Note that the new f ile is added to the Project Files list. Furthermore, a new t ab is o pened in t he
program editor area allowing you to enter the code.
Tip:
Ref erence material for developers is provided into the Laser Engine Language Reference section
of this Help system.
All the f iles that compose the project, are then synchronized when the project is executed, that is , t hey are
copied to the device before being executed. (See also Running a project).
Note that the f ile is added under the Resource files folder in the Project Files pane.
16
MANAGING PROJECTS
3
17
PROJECT EDITOR
3
o To copy the text, use the Edit > Copy menu command, or click the Copy button in t he
toolbar.
o To cut the text, use the Edit > Cut menu command, or click the Cut button in the
toolbar.
o To paste the text, use Edit > Paste menu command, or click the P aste but ton in t he
toolbar.
18
MANAGING PROJECTS
3
To go to a specific line:
1. From the Search menu, choose Go to line.
2. In the window that is displayed, enter the number of the line you want to move to and then c lick Go
to.
19
PROJECT EDITOR
3
20
MANAGING PROJECTS
3
Their purpose is to make it easier f or developers to create custom applications. For example, as an
integrator, you might need specific functions that these libraries provide.
Formatters have a .qs extension and are stored in the folder ...\Data\Formatters.
To prepare formatters:
1. From the Project Editor's menu bar, choose File > Formatters.
2. In the Project Files section, double click the f ormatter source f ile in order to access its code.
Alternatively, right-click Source Files and then click New Source File for creating a new one.
To use formatters:
1. In the layout, select one or more textual objects.
2. In the property section, set its Custom Formatters property to True.
3. Open the combo box named Script just below the preceeding property and set it with the file name
of the desired property.
21
PROJECT EDITOR
4
22
MANAGING PROJECTS
4
You can open a project that was saved locally, or a project that was saved t o a d evice. (S ee Opening a
project from a device).
To open a project
1. Do one of the following:
o From the Project Editor menu bar, choose File > Open project.
o From the Project Editor standard toolbar, click the Open project button.
2. In the Choose a project to open window that is displayed, browse to locate the .xqs p roject y ou
want to open.
3. Click on Open. The selected project and the related files are listed in the Project Files pane, and the
current source file appears in the programs editor area.
23
PROJECT EDITOR
4
o Choose File > Save Project (or click the button on the toolbar). The project is
automatically saved into the def ault folder, which depends on your operating s yst em. For
example, if you are using Windows 7, the def ault f older is ...
C:\Users\UserName\AppData\<Application Name>\Data.
Tip:
To locate the folder where projects are automatically saved in your system, do the following:
Access the system configuration registry (Start > Run, and then digit regedit.)
Navigate to HKEY_LOCAL_MACHINE\Software\Laservall\DataDirectory to see the
f older's path.
24
MANAGING PROJECTS
4
In order to interact to a device you must be connected with it (see Connecting to the device).
To delete a project:
1. From the Project Editor menu bar, choose File > Delete project in device.
2. In the window Laser device projects list window that is displayed, all projects that have been saved
to the device are listed. Select from the list the project you want to delete and click OK.
25
PROJECT EDITOR
5
26
CONNECTING TO DEVICE
5
In both cases, you can use the File menu to connect to the device.
Note:
If you have a Supervision installation of Laser Editor, all available devices are listed, b oth loc al
and remote (if enabled), while, if you have a Stand-alone installation, o nly local dev ic es are
listed. In the case of a remote device, the IP Address is also displayed.
3. Click OK.
Related topics:
• Running a project
• Testing a project
27
PROJECT EDITOR
5
When you are ready with your project (see Creating a project), you can run the program in two ways:
In order to test your projects you must switch to the Manual Mode. This way , t he Laser E ngine waits f or
commands rather than executing programs automatically.
28
CONNECTING TO DEVICE
5
Project Editor can be used to test your projects by executing them on the connected device.
Attention:
The simulation can only be done in Manual Mode. In Auto Mode the feature is not available and
the laser engraving is managed automatically through the Laser Engine (see Manual Mode vs .
Auto Mode).
Note:
When you press Run Project, a copy of the project that you are ex ec uting is aut omatically
saved to the device.
29
PROJECT EDITOR
6
Laser Engine is based on the ECMAScript scripting language, as defined in t he E CMA Script Language
Specification. Microsoft's JScript, and Netscape's JavaScript are also based on the ECMAScript standard.
Audience
This ref erence is addressed to developers who will use Project Editor to write their own programs in order t o
automate marking operations, and to customize Laser Editor so as to suit their environment specific needs.
Contents
This language ref erence is organized into the following sections:
Section Contents
Identif iers and reserved words What are identif iers and reserved keywords that you cannot use
Commenting the code How to comment the code within your programs
Declarations How to declare classes, functions, variables, and constants
A f ull description of the control statements and how to use t hem
Control Statements
in a program.
Classes and Methods (Member functions) What are classes and methods, and what are qualified names.
A description of the native and built-in objects that are s upplied
Native and Built-in Objects
with the Laser Engine Program for Applications.
Arguments variable How to use the arguments variables within functions.
A f ull description of the constants that are provided, whic h are
Built-in Constants
built into the Laser Engine Program.
A f ull description of the functions that are p rov ided, which are
Built-in Functions
built into the Laser Engine Program.
A f ull description of the operators that are provided, whic h are
Built-in Operators
built into the Laser Engine Program.
30
LASER ENGINE LANGUAGE REFERENCE
6
Laser Engine Program for Application's identifiers match the regex pattern [_A-Za-z][_A-Za-z0-9]*.
The rules f or the construction of identifiers are simple: you may use the 52 upper and lower case alphabetic
characters, the 10 digits and finally the underscore '_', which is considered to be an alphabetic character f or
this purpose. The only restriction is the usual one; identifiers must start with an alphabetic character.
Identif iers are used for variables, constants, class names, function names and labels.
See also:
• Declaring Classes
• Declaring Variables
• Declaring Constants
• Declaring Functions
Important notice:
You cannot use any of these reserved words as identifiers for variables, funct ions , methods, or
objects.
The f ollowing words are used as keywords in proposed extensions and are therefore reserved t o allow f or
the possibility of future adoption of those extensions:
• abstract
• boolean
• byte
• char
• class
• const
• debugger
• double
• enum
• export
• extends
• f inal
• f loat
• goto
• implements
• import
• int
• interf ace
• long
• native
• package
• private
31
PROJECT EDITOR
6
• protected
• public
• short
• static
• super
• synchronized
• throws
• transient
• volatile
Related topics:
• Declarations
• Classes and Methods (Member functions)
• Native and Built-in Objects
• Built-in Constants
32
LASER ENGINE LANGUAGE REFERENCE
6
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.
*/
33
PROJECT EDITOR
6
6.3 DECLARATIONS
This section describes how to declare classes, f unctions, variables and constants. They are declared
with class, function, var and const respectively.
In this section:
• Declaring Functions
• Declaring Classes
• Declaring Variables
• Declaring Constants
For example, the following code defines a simple function named square:
function square(number) {
return number * number;
}
Functions that don't operate on the this object ("static" methods) are typically stored as propert ies of t he
constructor function, not as properties of the prototype object. The same applies to constants, such as enum
values.
The f ollowing code defines a simple constructor function for a class called Person:
function Person(name)
{
this.name = name;
}
When def ining subclasses, there's a general pattern you can use. The f ollowing ex ample s hows how t o
create a subclass of Person called Employee:
34
LASER ENGINE LANGUAGE REFERENCE
6
Example:
function Employee(name, salary)
{
Person.call(this, name); // call base constructor
this.salary = salary;
}
// initialize prototype
Employee.prototype.toString = function() { ... }
Again, you can use the instanceof to verif y that the class relationship between
Employee and Person has been correctly established:
var a; // undefined
var c = "foliage"; // the string "foliage"
x = 1; // global variable
Tip:
Using global variables can make your code dif f icult to debug and maintain and is not
recommended.
Using the var keyword you can optionally initialize variables. If just the variableName is given, the variable
is created, but it has no value, that is, its value is undefined:
var variableName;
var anotherVariableName = InitialValue;
If an InitialValue is given, the variable is created and assigned this InitialValue. Variables declared
within f unctions are local to the function in which they are declared. Variables declared outside of f unct ions
and classes are global.
Example:
var i;
var count = 22;
var str = "string";
35
PROJECT EDITOR
6
Syntax:
const identifier = Value;
The const keyword is used to define constant values. The identifier is created as a constant wit h the
given Value. The constant is global unless defined within the scope of a class or function.
Constants must be defined at the point of declaration, because they cannot be changed later.
Constants are public global if they are declared outside of any enclosing braces. When declared wit hin t he
scope of some braces, that is, within an if statement, their scope is local to the enclosing block.
Example:
const PI2 = Math.PI * 2;
const COPYRIGHT = "Copyright (c) 2001";
36
LASER ENGINE LANGUAGE REFERENCE
6
Statements consist of keywords used with the appropriate syntax. A single st atement may s pan mult iple
lines. Multiple statements may occur on a single line if each statement is separated by a semicolon.
The f ollowing table summarizes the Laser Engine Program Control statements. Click the statement's name
f or detailed information:
Copyright
The material on Control Statements included in this Language Reference, is copy right (c ) 2005-2008 b y
Mozilla Development Center (MDC). MDC wikis have been prepared with the contributions of many authors ,
both within and outside the Mozilla Foundation. Unless otherwise indicated, the content is available primarily
under the terms and conditions set f orth in the Creative Commons: Attribution-Sharealike License,
v3.0 or later. Code samples are available under the terms of the MIT License. The latest versions of t hese
licenses are presently available here:
• Attribution-Sharealike License
• MIT License
37
PROJECT EDITOR
6
6.4.1 Break
Summary
Terminates the current loop, switch, or label statement and transfers program control to the
statement following the terminated statement.
Syntax
break [label];
Parameters
Parameter Description
label Identif ier associated with the label of the statement. If the statement is not a lo op or s witc h,
this is required.
Description
The break statement includes an optional label that allows the program to break out of a labeled statement.
The break statement needs to be nested within this labelled statement. The labelled statement can b e any
block statement; it does not have to be preceded by a loop statement.
Examples
The f ollowing function has a break statement that terminates the while loop when i is 3, and t hen ret urns
the value 3 * x.
function testBreak(x) {
var i = 0;
while (i < 6) {
if (i == 3) {
break;
}
i += 1;
}
return i * x;
}
Related topics:
• continue, switch
38
LASER ENGINE LANGUAGE REFERENCE
6
6.4.2 Const
Summary
Declares a read-only, named constant.
Syntax
const varname1 [= value1], varname2 [= value2], ..., varnameN [=
valueN];
Parameters
Parameter Description
varnameN Constant name. It can be any legal identifier.
valueN Value of the constant. It can be any legal expression.
Description
Creates a constant that can be global or local to the function in which it is declared. Const ants f ollow t he
same scope rules as variables.
The value of a constant cannot change through re-assignment, and a constant cannot be re-declared.
Because of this, although it is possible to declare a constant without initializing it, it would be useless t o d o
so.
A constant cannot share its name with a f unction or a variable in the same scope.
Examples
The f ollowing example produces the output "a is 7."
const a = 7;
print("a is " + a + ".");
Related topics:
• var
39
PROJECT EDITOR
6
6.4.3 Continue
Summary
Terminates execution of the statements in the current iteration of the current or labelled loop, and cont inues
execution of the loop with the next iteration.
Syntax
continue [label];
Parameters
Parameter Description
label Identif ier associated with the label of the statement
Description
In contrast to the break statement, continue does not terminate the execution of the loop entirely: instead,
• In a while loop, it jumps back to the condition.
• In a f or loop, it jumps to the update expression.
The continue statement can include an optional label that allows the program to jump to the next iterat ion
of a labelled loop statement instead of the current loop. In this case, the continue statement needs t o be
nested within this labelled statement.
Examples
The f ollowing example shows a while loop that has a continue statement that ex ecutes when t he v alue
of i is 3. Thus, n takes on the values 1, 3, 7, and 12.
i = 0;
n = 0;
while (i < 5) {
i++;
if (i == 3)
continue;
n += i;
}
40
LASER ENGINE LANGUAGE REFERENCE
6
If continue had a label of checkiandj, the program would continue at the top of
the checkiandj statement.
checkiandj:
while (i < 4) {
print(i );
i += 1;
checkj:
while (j > 4) {
print(j );
j -= 1;
if ((j % 2) == 0)
continue checkj;
print(j + " is odd.");
}
print("i = " + i);
print("j = " + j);
}
Related topics:
• break, label
41
PROJECT EDITOR
6
6.4.4 For
Summary
Creates a loop that consists of three optional expressions, enc los ed in parent heses and s eparated b y
semicolons, followed by a statement executed in the loop.
Syntax
for ([initial-expression]; [condition]; [final-expression])
statement
Parameters
Parameter Description
An expression (including assignment expressions) or variable declaration. Typically used to
initial- initialize a counter variable. This expression may optionally declare new variables with
expression the var keyword. These variables are not local to the loop, that is, t hey are in t he s ame
scope thefor loop is in. The result of this expression is discarded.
An expression to be evaluated before each loop iteration. If this expres sion ev aluates t o
true, statement is executed. This conditional test is optional. If o mitt ed, t he c ondit ion
condition
always evaluates to true. If the expression evaluates to false, execution s kips t o t he f irs t
expression following the for construct.
final- An expression to be evaluated at the end of each loop iteration. This occurs before the next
expression evaluation of condition. Generally used to update or increment the counter variable.
statement A statement that is executed as long as the condition evaluates to true.
Examples
The f ollowing for statement starts by declaring the variable i and initializing it to 0. It checks that i is les s
than nine, perf orms the two succeeding statements, and increments i by 1 after each pass through the loop:
42
LASER ENGINE LANGUAGE REFERENCE
6
6.4.5 Function
Summary
Declares a f unction with the specified parameters.
Syntax
function name([param] [, param] [..., param]) {
statements
}
Parameters
Parameter Description
name The f unction name.
param The name of an argument to be passed to the f unction. A f unction can have up to 255
arguments.
statements The statements which comprise the body of the function.
Description
To return a value, the f unction must have a return statement that specifies the value to return.
A f unction created with the function statement is a Function object and has all the properties, met hods ,
and behavior of Function objects.
A f unction can also be declared inside an expression. In this case the f unction is usually anonymous.
See f unction operator f or more information about the function (f unction expression).
Functions can be conditionally declared. That is, a function definition can be nested within an if statement .
Technically, such declarations are not actually function declarations; they are function expressions.
Examples
The f ollowing code declares a function that returns the total dollar amount of sales, when given the number
of units sold of products a, b, and c.
Related topics:
• Built-in Functions
43
PROJECT EDITOR
6
6.4.6 If...else
Summary
Executes a statement if a specified condition is true. If the condition is f alse, ano ther s tat ement can b e
executed.
Syntax
if (condition)
statement1
[else
statement2]
Parameters
Parameter Description
condition An expression that evaluates to true or false.
Statement that is executed if condition evaluates to true. Can be any statement, including
statement1
f urther nested if statements.
Statement that is executed if condition evaluates to false and the else clause exists. Can
statement2
be any statement, including block statements and further nested if statements.
Description
Multiple if...else statements can be nested to create an else if clause:
if (condition1)
statement1
else if (condition2)
statement2
else if (condition3)
statement3
...
else
statementN
To see how this works, this is how it would look like if the nesting were properly indented:
if (condition1)
statement1
else
if (condition2)
statement2
else
if (condition3)
...
44
LASER ENGINE LANGUAGE REFERENCE
6
Do not conf use the primitive boolean values true and false with the true and f alse values of
the Boolean object. Any value that is not undefined, null, 0, NaN, or the empty string (""), and any
object, including a Boolean object whose value is false, evaluates to true when p assed t o a c onditional
statement. For example:
Examples
if (x = y) {
/* do the right thing */
}
If you need to use an assignment in a conditional expression, a common practice is to put additional
parentheses around the assignment. For example:
if ((x = y)) {
/* do the right thing */
}
45
PROJECT EDITOR
6
6.4.7 Label
Summary
Provides a statement with an identifier that you can refer to using a break or continue statement.
For example, you can use a label to identify a loop, and then use the break or continue statement to indicate
whether a program should interrupt the loop or continue its execution.
Syntax
label :
statement
Parameters
Parameter Description
label Any Laser Engine Program identifier that is not a reserved word.
Statements. break can be used with any labeled statement, and continue can be used
statement
with looping labeled statements.
Examples
For an example of a label statement using break, see break. For an example of a label statement
using continue, see continue.
6.4.8 Return
Summary
Specifies the value to be returned by a function.
Syntax
return [expression];
Parameters
Parameter Description
expression The expression to return. If omitted, undefined is returned instead.
Examples
The f ollowing function returns the square of its argument, x, where x is a number.
function square(x) {
return x * x;
}
46
LASER ENGINE LANGUAGE REFERENCE
6
6.4.9 Switch
Summary
Evaluates an expression, matching the expression's value to a case label, and executes statements
associated with that case.
Syntax
switch (expression) {
case label1:
statements1
[break;]
case label2:
statements2
[break;]
...
case labelN:
statementsN
[break;]
default:
statements_def
[break;]
}
Parameters
Parameter Description
expression An expression matched against each label.
labelN Identif ier used to match against expression.
statementsN Statements that are executed if expression matches the associated label.
statements_def Statements that are executed if expression does not match any label.
Description
If a match is found, the program executes the associated statements. If multiple cases match t he provided
value, the f irst case that matches is selected, even if the cases are not equal to each other.
The program first looks for a case clause with a label matching the value of expression and then t ransfers
control to that clause, executing the associated statements. If no matching label is found, the program lo oks
f or the optional default clause, and if found, transfers control to that clause, ex ecut ing t he as sociat ed
statements. If no default clause is found, the program continues execution at the statement following t he
end of switch. By convention, the default clause is the last clause, but it does not need to be so.
The optional break statement associated with each case label ensures that the program breaks out of switch
once the matched statement is executed and continues execution at the statement f ollowing switch.
If break is omitted, the program continues execution at the next statement in the switch statement.
47
PROJECT EDITOR
6
Examples
In the f ollowing example, if expression evaluates to "Bananas", the program matches t he value wit h cas e
"Bananas" and executes the associated statement. When break is encountered, the program break s out
of switch and executes the statement following switch. If break were omitted, t he st atement f or c ase
"Cherries" would also be executed.
switch (expr) {
case "Oranges":
print("Oranges are $0.59 a pound.");
break;
case "Apples":
print("Apples are $0.32 a pound.");
break;
case "Bananas":
print("Bananas are $0.48 a pound.");
break;
case "Cherries":
print("Cherries are $3.00 a pound.");
break;
case "Mangoes":
case "Papayas":
print("Mangoes and papayas are $2.79 a pound.");
break;
default:
print("Sorry, we are out of " + expr + ".");
}
print("Is there anything else you'd like?");
48
LASER ENGINE LANGUAGE REFERENCE
6
6.4.10 Throw
Summary
Throws a user-def ined exception.
Syntax
throw expression;
Parameters
Parameter Description
expression The expression to throw.
Description
Use the throw statement to throw an exception. When you throw an exception, expression specif ies t he
value of the exception. Each of the following throws an exception:
Examples
Throw an object
You can specify an object when you throw an exception. You can then ref erence the object' s pro pert ies in
the catch block. The f ollowing example creates an object myUserException of
type UserException and uses it in a throw statement.
function UserException(message) {
this.message = message;
this.name = "UserException";
}
function getMonthName(mo) {
mo = mo-1; // Adjust month number for array index (1=Jan,
12=Dec)
var months = new Array("Jan", "Feb", "Mar", "Apr", "May",
"Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
if (months[mo] != null) {
return months[mo];
} else {
myUserException = new UserException("InvalidMonthNo");
throw myUserException;
}
}
try {
// statements to try
monthName = getMonthName(myMonth);
} catch (e) {
monthName = "unknown";
logMyErrors(e.message, e.name); // pass exception object to
err handler
}
49
PROJECT EDITOR
6
/*
* Creates a ZipCode object.
*
* Accepted formats for a zip code are:
* 12345
* 12345-6789
* 123456789
* 12345 6789
*
* If the argument passed to the ZipCode constructor does not
* conform to one of these patterns, an exception is thrown.
*/
function ZipCode(zip) {
zip = new String(zip);
pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
if (pattern.test(zip)) {
// zip code value will be the first match in the string
this.value = zip.match(pattern)[0];
this.valueOf = function() {
return this.value
};
this.toString = function() {
return String(this.value)
};
} else {
throw new ZipCodeFormatException(zip);
}
}
function ZipCodeFormatException(value) {
this.value = value;
this.message = "does not conform to the expected format for a
zip code";
this.toString = function() {
return this.value + this.message
};
}
/*
* This could be in a script that validates address data
* for US addresses.
*/
function verifyZipCode(z) {
try {
z = new ZipCode(z);
} catch (e) {
if (e instanceof ZipCodeFormatException) {
return ZIPCODE_INVALID;
} else {
50
LASER ENGINE LANGUAGE REFERENCE
6
return ZIPCODE_UNKNOWN_ERROR;
}
}
return z;
}
Rethrow an exception
You can use throw to rethrow an exception after you catch it. The f ollowing example catches an ex c ept ion
with a numeric value and rethrows it if the value is over 50. The rethrown exception propagates up t o t he
enclosing function or to the top level so that the user sees it.
try {
throw n; // throws an exception with a numeric value
} catch (e) {
if (e <= 50) {
// statements to handle exceptions 1-50
} else {
// cannot handle this exception, so rethrow
throw e;
}
}
51
PROJECT EDITOR
6
6.4.11 Try...catch
Summary
Marks a block of statements to try, and specifies a response, should an exception be thrown.
Syntax
try {
try_statements
}
[catch (exception_var_1 if condition_1) {
catch_statements_1
}]
...
[catch (exception_var_2) {
catch_statements_2
}]
[finally {
finally_statements
}]
Parameters
Parameter Description
try_statements The statements to be executed.
catch_statements_1,
Statements that are executed if an exception is thrown in the try block.
catch_statements_2
exception_var_1,
An identifier to hold an exception object for the associated catch clause.
exception_var_2
condition_1 A conditional expression.
Statements that are executed after the try statement complet es . Thes e
finally_statements statements execute regardless of whether or not an exception was thrown
or caught.
Description
The try statement consists of a try block, which contains one or more statements, and at least
one catch clause or a finally clause, or both. That is, there are three f orms of the try statement:
1. try...catch
2. try...finally
3. try...catch...finally
A catch clause contain statements that specify what to do if an exception is thrown in the try block. That is,
you want the try block to succeed, and if it does not succeed, you want control to pass to the catch bloc k.
If any statement within the try block (or in a function called from within the try block) throws an except ion,
control immediately shifts to the catch clause. If no exception is thrown in the try block, the catch c lause
is skipped.
The finally clause executes after the try block and catch clause(s) execute but before the s tatements
f ollowing the try statement. It always executes, regardless of whether or not an exception was t hrown or
caught.
You can nest one or more try statements. If an inner try statement does not hav e a catch c lause, t he
enclosing try statement's catch clause is entered.
You also use the try statement to handle Java exceptions.
52
LASER ENGINE LANGUAGE REFERENCE
6
try {
throw "myException"; // generates an exception
}
catch (e) {
// statements to handle any exceptions
logMyErrors(e); // pass exception object to error handler
}
This identifier is local to the catch clause. That is, it is created when the catch clause is entered, and af t er
the catch clause finishes executing, the identifier is no longer available.
You can use the finally clause to make your script fail gracefully when an exception occurs; for example,
you may need to release a resource that your script has tied up. The f ollowing example opens a f ile and then
executes statements that use the file (server-side Laser Engine Program allows you to acc ess f iles ). If an
exception is thrown while the file is open, the finally clause closes the file before the script fails.
openMyFile()
try {
// tie up a resource
writeMyFile(theData);
}
finally {
closeMyFile(); // always close the resource
}
Examples:
See the examples for throw
53
PROJECT EDITOR
6
6.4.12 Var
Summary
Declares a variable, optionally initializing it to a value.
Syntax
var varname1 [= value1], varname2 [= value2], ..., varnameN [=
valueN];
Parameters
Parameter Description
varnameN Variable name. It can be any legal identifier.
valueN Initial value of the variable. It can be any legal expression.
Description
The scope of a variable is the current function or, for variables declared out side a f unct ion, t he current
application.
Using var outside a function is optional; assigning a value to an undeclared variable implicitly declares it as
a global variable. However, it is recommended to always use var, and it is necessary within functions in t he
f ollowing situations:
• If a variable in a scope containing the function (including the global scope) has the same name.
• If recursive or multiple functions use variables with the same name and intend those variables t o be
local.
Failure to declare the variable in these cases will very likely lead to unexpected results.
Examples
The f ollowing example declares two variables, num_hits and cust_no, and initializes both to the value 0.
54
LASER ENGINE LANGUAGE REFERENCE
6
6.4.13 While
Summary
Creates a loop that executes a specified statement as long as the test condition ev aluat es t o t rue. The
condition is evaluated before executing the statement.
Syntax
while (condition)
statement
Parameters
Parameter Description
An expression evaluated before each pass through the loop. If this condition evaluates t o
condition true, statement is executed. When condition evaluates to false, execution c ont inues wit h
the statement after the while loop.
statement A statement that is executed as long as the condition evaluates to true.
Examples
The f ollowing while loop iterates as long as n is less than three.
n = 0;
x = 0;
while (n < 3) {
n ++;
x += n;
}
Each iteration, the loop increments n and adds it to x. Therefore, x and n take on the following values:
• Af ter the first pass: n = 1 and x = 1
• Af ter the second pass: n = 2 and x = 3
• Af ter the third pass: n = 3 and x = 6
Af ter completing the third pass, the condition n < 3 is no longer true, so the loop terminates.
55
PROJECT EDITOR
6
6.4.14 With
Summary
Extends the scope chain for a statement.
Syntax
with (object)
statement
Parameters
Parameter Description
object Adds the given object to the scope chain used when evaluating the statement. The
parentheses around object are required.
statement Any statement.
Description
Laser Engine Program looks up an unqualif ied name by searching a scope chain associated with the
execution context of the script or function containing that unqualified name. The 'with' st atement adds t he
given object to the head of this scope chain during the evaluation of its statement body. If an unq ualif ied
name used in the body matches a property in the scope chain, then the name is bound to the propert y and
the object containing the property. Otherwise a 'ReferenceError' is thrown.
Ambiguity Con
• Con: 'with' makes it hard for a human reader or Laser Engine Program compiler to decide whether
an unqualif ied name will be found along the scope chain, and if so, in which object . S o given t his
example:
function f(x, o) {
with (o)
print(x);
}
only when f is called is x either f ound or not, and if found, either in o or (if no such propert y ex is ts) in f's
activation object, where x names the f irst formal argument. If you forget to define x in the object you pass as
the second argument, or if there's some similar bug or confusion, you won't get an error -- jus t unexpect ed
results.
56
LASER ENGINE LANGUAGE REFERENCE
6
Examples
The f ollowing with statement specifies that the Math object is the default object. The statements f ollowing
the with statement refer to the PI property and the cos and sin methods, without specif ying an object .
Laser Engine Program assumes the Math object for these references.
var a, x, y;
var r = 10;
with (Math) {
a = PI * r * r;
x = r * cos(PI);
y = r * sin(PI / 2);
}
57
PROJECT EDITOR
6
For example, in a Laser Engine Program GUI application, every application object belongs to
the Application object. This can lead to some rather lengthy code, f or
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, Laser Engine Program is intelligent enough to work out the fully qualified name, so the code y ou
would actually write is simply ListBox.count. The only time that you need to qualify your names is when
an unqualif ied name is ambiguous.
The class Object does not define the variable myProperty, but since the class supports propert ies, we
can def ine the variable with that name on the fly and use it later. Properties are associated wit h t he o bject
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 p roperty , unless explicitly
stated.
58
LASER ENGINE LANGUAGE REFERENCE
6
Objects Description
This set of objects is supplied by the Laser Engine Program implementat ion. S ome
Native Objects native objects are built-in, while other may be constructed during the course of
execution of a Laser Engine Program.
Graphical User This set of objects allows defining the graphical interface of the applic ation (dialogs,
Interf ace Objects checkbox, buttons, and so forth).
Base System This set of objects allows def ining the system interf ace, as well as accessing
Objects directories and files, or interacting with external programs.
Laser Graphical This set of objects allows managing the documents and all of the graphic objects t hey
Objects may contain (arrays, codes, strings, and so forth).
Laser System This set of objects allows managing the low-level laser system, that is, axis movement
Objects and I/O modules.
Related topics:
• Built-in Constants
• Built-in Functions
• Control Statements
Copyright
Portions of the following content is copyright (c) 2005-2008 by Mozilla Development Cent er (MDC). MDC
wikis have been prepared with the contributions of many authors, both within and outside the Mozilla
Foundation. Unless otherwise indicated, the content is available primarily under the terms and conditions set
f orth in the Creative Commons: Attribution-Sharealike License, v3.0 or later. Code samples are available
under the terms of the MIT License. The latest versions of these licenses are presently available here:
• Attribution-Sharealike License
• MIT License
59
PROJECT EDITOR
6
Math
The built-in Math object provides a variety of f unctions, including all the common mathematical
f unctions. More...
Math Functions
Number Number Math::abs ( Number number );
Number Math::acos ( Number number );
Number Math::asin ( Number number );
Number Math::atan ( Number number );
Number Math::atan2 ( Number yCoord, Number xCoord );
Number Math::ceil ( Number number );
Number Math::cos ( Number number );
Number Math::exp ( Number number );
Number Math::floor ( Number number );
Number Math::log ( Number number );
Number Math::max ( Number number1, Number number2 );
Number Math::min ( Number number1, Number number2 );
Number Math::pow ( Number number, Number power);
Number Math::random ( );
Number Math::round ( Number number );
Number Math::sin ( Number number );
Number Math::sqrt ( Number number );
Number Math::tan ( Number number );
Math Properties
Number E
Number LN2
Number LN10
Number LOG2E
Number LOG10E
Number PI
Number SQRT1_2
Number SQRT2
Detailed description
The built-in Math object provides a variety of functions, including all the common mathematical functions.
The Math object always exists in a Laser Engine program. Use the Math objec t t o ac cess mat hematical
constants and functions, for example.
var x, angle, y;
with ( Math ) {
x = PI * 2;
angle = 1.3;
y = x * sin( angle );
}
60
LASER ENGINE LANGUAGE REFERENCE
6
var x = -99;
var y = 99;
with ( Math ) {
x = abs( x );
y = abs( y );
}
if ( x == y )
print( "equal" );
Math::acos ( Number number );
Returns the arccosine of the given number in radians between 0 and Math.PI. If t he number is out of
range, returns NaN.
Math::asin ( Number number );
Returns the arcsine of the given number in radians between -Math.PI/2 and Math.PI/2. If the number
is out of range, returns NaN
Math::atan ( Number number );
Returns the arctangent of the given number in radians between -Math.PI/2 and Math.PI/2. If the
number is out of range, returns NaN.
Math::atan2 ( Number yCoord, Number xCoord );
Returns the counter-clockwise angle in radians between the positive x-ax is and t he point at (xCoord,
yCoord). The value returned is always between -Math.PI and Math.PI.
function polar( x, y )
{
return Math.atan2( y, x );
}
Math::ceil ( Number number );
If the number is an integer, it returns the number. If the number is a f loating point value, it returns the
smallest integer greater than the number.
var x = 913.41;
x = Math.ceil( x ); // x == 914
var y = -33.97;
y = Math.ceil( y ); // y == -33
Math::cos ( Number number );
Returns the cosine of the given number. The value will be in the range -1..1.
61
PROJECT EDITOR
6
62
LASER ENGINE LANGUAGE REFERENCE
6
E
Eulers constant. The base for natural logarithms.
LN2
Natural logarithm of 2.
LN10
Natural logarithm of 10.
LOG2E
Base 2 logarithm of E.
LOG10E
Base 10 logarithm of E.
PI
Ratio of the circumference of a circle to its diameter.
SQRT1_2
Square root of 1/2; equivalently, 1 over the square root of 2.
SQRT2
Square root of 2.
63
PROJECT EDITOR
6
Array
An Array is a datatype which contains a named list of items. More...
Array functions
Array Array::concat ( Array a1, Array a2 ... aN );
String Array::join ( String optSeparator );
Object Array::pop ( );
Number Array::push ( item1, optItem2, ... optItemN );
void Array::reverse ( );
Object Array::shift ( );
Array Array::slice ( Number startIndex, Number optEndIndex );
Number Array::sort ( Function optComparisonFunction );
Array Array::splice ( Number startIndex, Number replacementCount, optItem1, ... optItemN );
String Array::toString ( );
Number Array::unshift ( String expression, optExpression1, ... optExpressionN );
Array properties
Number length
Detailed description
An Array is a datatype which contains a named list of items. The items can be any Las er E ngine o bject .
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 perf orm a deep copy on items that
are Number or String objects, and a shallow copy on other objects.
64
LASER ENGINE LANGUAGE REFERENCE
6
Array access
Array items are accessed via their names. Names can be either integers or strings.
var m2 = mammals[2];
mammals[2] = "gorilla";
var thing = things[2][1]
The f irst 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 tothing, 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 bracket operator ([]) or by directly dereferencing t he array object
and specifying the property name (.name). These two accessor types can be mixed f reely as s een below
with theaddress and phoneNumber properties:
65
PROJECT EDITOR
6
For customized sorting, pass the sort() function a comparison function, optComparisonFunction, t hat
has the f ollowing signature and behavior:
66
LASER ENGINE LANGUAGE REFERENCE
6
Property documentation
length
Holds the number of items in the array. Items with string keys are excluded from the length property.
67
PROJECT EDITOR
6
Boolean
Laser Engine Program provides a Boolean data type. More...
Boolean functions
String Boolean::toString ( );
Boolean Boolean::valueOf ( );
Detailed description
Laser Engine Program 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 c an be ev aluat ed in a
boolean context, for example, in an if statement.
If the expression's value is 0, null, false, NaN, undef ined or the empty string "", the expression
is false; otherwise the expression is true.
68
LASER ENGINE LANGUAGE REFERENCE
6
Date
Instances of the Date class are used to store and manipulate dates and times. More...
Static date functions
Number Date::parse ( String dateString );
Number Date::UTC (year, month[, date[, hrs[, min[, sec[, ms]]]]] )
Date functions
Number Date::getDate ( );
Number Date::getDay ( );
Number Date::getFullYear ( );
Number Date::getHours ( );
Number Date::getMilliseconds ( );
Number Date::getMinutes ( );
Number Date::getMonth ( );
Number Date::getSeconds ( );
Number Date::getTime ( );
Number Date::getTimezoneOffset ( );
void Date::setDate ( Number dayOfTheMonth );
void Date::setFullYear ( yearValue[, monthValue[, dayValue]] );
void Date::setHours ( Number hour );
void Date::setMilliseconds ( Number milliseconds );
void Date::setMinutes ( Number minutes );
void Date::setMonth ( Number month );
void Date::setSeconds ( );
void Date::setTime ( Number milliseconds );
String Date::toString ( );
String Date::toDateString ( );
String Date::toTimeString ( );
String Date::toLocaleString ( );
String Date::toLocaleDateString ( );
String Date::toLocaleTimeString ( );
Number Date::valueOf ( );
Number Date::getUTCDate ( );
Number Date::getUTCDay ( );
Number Date::getUTCFullYear ( );
Number Date::getUTCHours ( );
Number Date::getUTCMilliseconds ( );
Number Date::getUTCMinutes ( );
Number Date::getUTCMonth ( );
Number Date::getUTCSeconds ( );
void Date::setUTCDate ( dayvalue );
void Date::setUTCFullYear ( yearValue[, monthValue[, dayValue]] );
void Date::setUTCHours ( hoursValue[, minutesValue[, secondsValue[, msValue]]] );
void Date::setUTCMilliseconds ( millisecondsValue );
void Date::setUTCMinutes ( minutesValue[, secondsValue[, msValue]] );
void Date::setUTCMonth ( monthValue[, dayValue] );
void Date::setUTCSeconds ( secondsValue[, msValue] );
String Date::toUTCString ( );
69
PROJECT EDITOR
6
Detailed description
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 relev ant part s (s ee D ate f unct ions). A
complementary variety of set functions are also provided (such as, for example, setDate or setYear).
The f unctions operate using local time. Conversion between Date objects to and from strings are p rov ided
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();
Date()
Date( milliseconds )
Date( year, month, day, optHour, optMinutes, optSeconds,
optMilliseconds )
70
LASER ENGINE LANGUAGE REFERENCE
6
You should specify a full year for the year; for example, 1998. If a year between 0 and 99 is spec if ied, t he
method converts the year to a year in the 20th century (1900 + year); for example, if you specify 95, the year
1995 is used.
The UTC method differs from the Date constructor in two ways.
If a parameter you specify is outside of the expected range, the UTC method updates the other parameters to
allow f or your number. For example, if you use 15 for month, the year will be incremented b y 1 (y ear + 1),
and 3 will be used for the month.
Because UTC is a static method of Date, you always use it as Date.UTC(), rat her t han as a met hod of
a Date object you created.
The f ollowing statement creates a Date object using GMT instead of local time:
The f ollowing example assigns the four-digit value of the current year to the variable yr.
var today = new Date();
var yr = today.getFullYear();
Date::getHours ( );
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.getHours(); // x == 22
71
PROJECT EDITOR
6
Date::getMilliseconds ( );
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 );
var x = d.getMilliseconds(); // x == 0
Date::getMinutes ( );
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.getMinutes(); // x == 30
Date::getMonth ( );
Returns the month component of the date using local time. The value is always in the range 1..12.
var d = new Date( 1975, 12, 25, 22, 30 );
var x = d.getMonth(); // x == 12
72
LASER ENGINE LANGUAGE REFERENCE
6
monthValue - An integer between 0 and 11 representing the months January through December
dayValue - An integer between 1 and 31 representing the day of the month. If you specif y
the dayValue parameter, you must also specify the monthValue
If you do not specif y the monthValue and dayValue parameters, the values returned f rom
the getMonth and getDate methods are used.
theBigDay = new Date();
theBigDay.setFullYear(1997);
Date::setHours ( Number hour );
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.setHours( 10 ); // d == 1980-12-30T10:30:00
Date::setMilliseconds ( Number milliseconds );
Sets the milliseconds component of the date to the specified value in local time.
var d = new Date( 1975, 12, 25, 22, 30 );
d.setMilliseconds( 998 ); // d == 1980-12-30T10:30:00:998
Date::setMinutes ( Number minutes );
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.setMinutes( 15 ); // d == 1980-12-30T10:15:00
Date::setMonth ( Number month );
Sets the month to the specified month, which must be in the range 0..11, in local time.
var d = new Date( 1975, 12, 25, 22, 30 );
d.setMonth(0); // d == 1980-01-11T22:30:00
Date::setSeconds ( );
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 );
d.setSeconds( 25 ); // d == 1980-12-30T22:30:25
Date::setTime ( Number milliseconds );
Sets the date and time to the local date and time given in terms of milliseconds since midnight o n t he 1st
January 1970.
var d = new Date( 1975, 12, 25, 22, 30 );
var duplicate = new Date();
duplicate.setTime( d.getTime() );
Date::toString ( );
Converts the date into a string on the ISO 8601 extended format: YYYY-MM-DDTHH:MM:SS.
var d = new Date( 1975, 12, 25, 22, 30 );
var s = d.toString(); // s == "1975-12-25T22:30:00"
Date::toDateString ( );
Returns the date portion of a Date object in human readable form.
var d = new Date(1993, 6, 28, 14, 39, 7);
println(d.toString()); // prints Wed Jul 28 1993 14:39:07 GMT-
0600 (PDT)
println(d.toDateString()); // prints Wed Jul 28 1993
Date::toTimeString ( );
Returns the time portion of a Date object in human readable form.
73
PROJECT EDITOR
6
The toLocaleString method converts the date to a string using the formatting convention of the operating
system where the script is running. If the operating system is not year-2000 compliant and does not us e t he
f ull year f or years bef ore 1900 or over 2000, toLocaleString returns a string that is not year-2000
compliant.toLocaleString behaves similarly to toString when converting a y ear t hat t he operat ing
system does not properly format.
Methods such as getHours, getMinutes, and getSeconds give more portable results
than toLocaleString.
In the f ollowing example, today is a Date object:
today = new Date(95,11,18,17,28,35); //months are represented by
0 to 11
today.toLocaleString();
In this example, toLocaleString returns a string value that is similar to the f ollowing f orm. The ex ac t
f ormat depends on the platform.
12/18/95 17:28:35
Date::toLocaleDateString ( );
Converts a date to a string, returning the date portion using the operating system's locale's conventions.
The toLocaleDateString method converts the date to a string using the formatting c onvention of t he
operating system where the script is running. If the operating system is not year-2000 compliant and d oes
not use the f ull year for years before 1900 or over 2000, toLocaleDateString returns a string that is not
year-2000 compliant. toLocaleString behaves similarly to toString when converting a y ear t hat t he
operating system does not properly format.
Methods such as getHours, getMinutes, and getSeconds give more portable results
than toLocaleDateString
The toLocaleTimeString method converts the date to a string using the formatting c onvention of t he
operating system where the script is running. If the operating system is not year-2000 compliant and d oes
not use the f ull year for years before 1900 or over 2000, toLocaleDateString returns a string that is not
year-2000 compliant. toLocaleString behaves similarly to toString when converting a y ear t hat t he
operating system does not properly format.
74
LASER ENGINE LANGUAGE REFERENCE
6
Methods such as getHours, getMinutes, and getSeconds give more portable results
than toLocaleDateString. Use toLocaleTimeString when then intent is t o d is play to t he us er a
string formatted using the regional format chosen by the user. Be aware that this method, due to it s nat ure,
behaves differently depending on the operating system and on the user's settings.
today.toLocaleDateString()
Date::valueOf ( );
Returns the primitive value of a Date object as a number data t y pe, t he number o f milliseconds s ince
midnight 01 January, 1970 UTC.
This method is functionally equivalent to the getTime method. This method is usually called int ernally by
Laser Engine Program and not explicitly in code.
See also:
Date::getTime ( );
x = new Date(56, 6, 17);
myVar = x.valueOf(); //assigns -424713600000 to myVar
Date::getUTCDate ( );
Returns the day (date) of the month in the specified date according to universal time. The v alue ret urned
by getUTCDate is an integer between 1 and 31.
The f ollowing example assigns the day portion of the current date to the variable d.
var d;
Today = new Date();
d = Today.getUTCDate();
Date::getUTCDay ( );
Returns the day of the week in the specif ied date according to universal time. The value returned
by getUTCDay is an integer corresponding to the day of the week: 0 f or S unday , 1 f or Monday, 2 f or
Tuesday, and so on.
The f ollowing example assigns the weekday portion of the current date to the variable weekday.
var weekday;
Today = new Date()
weekday = Today.getUTCDay()
Date::getUTCFullYear ( );
Returns the year in the specif ied date according to universal time. The value returned
by getUTCFullYear is an absolute number that is compliant with year-2000, for example, 1995.
The f ollowing example assigns the four-digit value of the current year to the variable yr.
var yr;
Today = new Date();
yr = Today.getUTCFullYear();
Date::getUTCHours ( );
Returns the hours in the specified date according to universal time. The value returned by getUTCHours is
an integer between 0 and 23.
The f ollowing example assigns the hours portion of the current time to the variable hrs.
75
PROJECT EDITOR
6
var hrs;
The f ollowing example assigns the milliseconds portion of the current time to the variable ms.
var ms;
Today = new Date();
ms = Today.getUTCMilliseconds();
Date::getUTCMinutes ( );
Returns the minutes in the specif ied date according to universal time. The value returned
by getUTCMinutes is an integer between 0 and 59.
The f ollowing example assigns the minutes portion of the current time to the variable min.
var min;
Today = new Date();
min = Today.getUTCMinutes();
Date::getUTCMonth ( );
Returns the month of the specified date according to universal time. The value returned by getUTCMonth is
an integer between 0 and 11 corresponding to the month. 0 for January, 1 f or February, 2 for March, and s o
on.
The f ollowing example assigns the month portion of the current date to the variable mon.
var mon;
Today = new Date();
mon = Today.getUTCMonth();
Date::getUTCSeconds ( );
Returns the seconds in the specif ied date according to universal time. The value returned
by getUTCSeconds is an integer between 0 and 59.
The f ollowing example assigns the seconds portion of the current time to the variable sec.
var sec;
Today = new Date();
sec = Today.getUTCSeconds();
Date::setUTCDate ( dayvalue );
Sets the day of the month for a specified date according to universal time.
Parameter
dayvalue - An integer from 1 to 31, representing the day of the month.
If a parameter you specify is outside of the expected range, setUTCDate at t empt s t o updat e t he d ate
inf ormation in the Date object accordingly. For example, if you use 40 for dayValue, and the month stored
in the Date object is June, the day will be changed to 10 and the month will be incremented to July
theBigDay = new Date();
theBigDay.setUTCDate(20);
76
LASER ENGINE LANGUAGE REFERENCE
6
77
PROJECT EDITOR
6
78
LASER ENGINE LANGUAGE REFERENCE
6
Number
A Number is a datatype that represents a number. In most situations, programmers will use numeric lit erals
like 3.142 directly in code. More...
Number functions
String Number::toString ( [radix] );
String Number::toExponential ( [fractionDigits] );
String Number::toFixed ( [Digits] );
String Number::toLocaleString ( );
String Number::toPrecision ( [ precision ] );
Number Number::valueOf ( );
Number properties
Number MAX_VALUE
Number MIN_VALUE
Number NaN
Number NEGATIVE_INFINITY
Number POSITIVE_INFINITY
Detailed description
A Number is a datatype that represents a number. In most situations, programmers will use numeric lit erals
like 3.142 directly in code.
The Number datatype is useful for obtaining system limit s, e.g. MIN_VALUE and MAX_VALUE, and f or
perf orming number to string conversions with toString()
var x = 3.142;
The toString method parses its f irst argument, and attempts to return a string representation in the
specified radix (base). For radixes above 10, the letters of the alphabet indicate numerals great er t han 9.
For example, for hexadecimal numbers (base 16), A through F are used.
If toString is given a radix not between 2 and 36, an exception is thrown. If the radix is not specified, Laser
Engine Program assumes the preferred radix is 10.
79
PROJECT EDITOR
6
var x = 7;
print(x.toString(2)); // displays "111"
Number::toExponential ( [fractionDigits] );
Returns a string representing the Number object in exponential notation
Parameter:
fracionDigits - An integer specifying the number of digits after the decimal point. Defaults to as many
digits as necessary to specify the number.
See also:
Number::toFixed ( [Digits] );
This method returns a string representing a Number object in exponential notation with one digit bef ore t he
decimal point, rounded to fractionDigits digits af ter the decimal point. If
the fractionDigits argument is omitted, the number of digits after t he d ecimal point d ef aults to t he
number of digits necessary to represent the value uniquely.
If you use the toExponential method for a numeric literal and the numeric literal has no exponent and no
decimal point, leave a space before the dot that precedes the method call t o prevent t he dot f rom being
interpreted as a decimal point.
If a number has more digits that requested by the fractionDigits parameter, the number is ro unded t o
the nearest number represented by fractionDigits digits. See the discussion of rounding in the
description of the toFixed method, which also applies to toExponential.
var num=77.1234;
print("num.toExponential() is " + num.toExponential()); //
displays 7.71234e+1
print("num.toExponential(4) is " + num.toExponential(4)); //
displays 7.7123e+1
print("num.toExponential(2) is " + num.toExponential(2)); //
displays 7.71e+1
print("77.1234.toExponential() is " + 77.1234.toExponential());
//displays 7.71234e+1
print("77 .toExponential() is " + 77 .toExponential()); //
displays 7.7e+1
var x = 7;
Number::toFixed ( [Digits] );
Formats a number using fixed-point notation.
Parameter:
Digits - The number of digits to appear after the decimal point; this may be a value between 0 and 20,
inclusive, and implementations may optionally support a larger range of values. If t his arg ument is
omitted, it is treated as 0.
This method returns a string representation of number that does not use exponential notation and has
exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is
padded with zeros if necessary so that it has the specified length. If number is g reater t han 1e+ 21, t his
method simply calls Number.toString() and returns a string in exponential notation.
80
LASER ENGINE LANGUAGE REFERENCE
6
var n = 12345.6789;
n.toFixed(); // Returns 12346: note rounding, no
fractional part
n.toFixed(1); // Returns 12345.7: note rounding
n.toFixed(6); // Returns 12345.678900: note added
zeros
(1.23e+20).toFixed(2); // Returns 123000000000000000000.00
(1.23e-10).toFixed(2) // Returns 0.00
Number::toLocaleString ( );
Returns a human readable string representing the number using the locale of the environment.
Number::toPrecision ( [ precision ] );
Returns a string representing the Number object to the specified precision.
Parameter:
precision - An integer specifying the number of significant digits.
See also:
Number::toFixed ( [Digits] );, Number::toString ( [radix] );
This method returns a string representing a Number object in fixed-point or exponential notation rounded t o
precision significant digits. See the discussion of rounding in the description of the toFixed method, which
also applies to toPrecision.
If the precision argument is omitted, behaves as toString. If it is a non-integer v alue, it is ro unded t o the
nearest integer. After rounding, if that value is not between 1 and 100 (inclusive), a RangeError is thrown.
81
PROJECT EDITOR
6
A value representing the negative Inf inity value. Several Laser Engine Program methods (such as
the Number constructor, parseFloat, and parseInt) return NaN if the value specified in the parameter is
significantly lower than Number.MIN_VALUE.
In the f ollowing example, the variable smallNumber is assigned a value that is smaller than t he minimum
value. When the if statement executes, smallNumber has the value "-Infinity", so smallNumber is
set to a more manageable value before continuing:
var smallNumber = (-Number.MAX_VALUE) * 2
if (smallNumber == Number.NEGATIVE_INFINITY) {
smallNumber = returnFinite();
}
POSITIVE_INFINITY
A value representing the negative Infinity value. Several Laser Engine Program methods (such as
the Number constructor, parseFloat, and parseInt) return NaN if the value specified in the parameter is
significantly lower than Number.MIN_VALUE.
In the f ollowing example, the variable smallNumber is assigned a value that is smaller than t he minimum
value. When the if statement executes, smallNumber has the value "-Infinity", so smallNumber is
set to a more manageable value before continuing:
var smallNumber = (-Number.MAX_VALUE) * 2
if (smallNumber == Number.NEGATIVE_INFINITY) {
smallNumber = returnFinite();
}
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.
82
LASER ENGINE LANGUAGE REFERENCE
6
1.3.1.2 RegExp
Creates a regular expression object for matching text according to a pattern. More...
RegExp Functions
The global RegExp object has no methods of its own, however, it does inherit some met hods t hrough t he
prototype chain.
RegExp Properties
(*ptFunction) constructor
Boolean global
Boolean ignoreCase
Number lastIndex
Boolean multiline
String source
Detailed description
Creates a regular expression object for matching text according to a pattern.
var regex = new RegExp("pattern" [, "flags"]);
var literal = /pattern/flags;
When using the constructor function, the normal string escape rules (preceding s pecial charac ters with \
when included in a string) are necessary. For example, the following are equivalent:
var re = new RegExp("\\w+");
var re = /\w+/;
Notice that the parameters to the literal format do not use quotation marks to ind ic ate s trings, while t he
parameters to the constructor function do use quotation marks. So the following expressions create the same
regular expression:
/ab+c/i;
new RegExp("ab+c", "i");
Matches beginning of input. If the multiline flag is set to true, also matches immediately aft er
^ a line break character.
For example, /^A/ does not match the 'A' in "an A", but does match the first 'A' in "An A."
83
PROJECT EDITOR
6
Matches end of input. If the multiline flag is set to true, also matches immediately bef ore a
$ line break character.
For example, /t$/ does not match the 't' in "eater", but does match it in "eat".
Matches the preceding item 0 or more times.
* For example, /bo*/ matches 'boooo' in "A ghost booooed" and 'b' in "A bird warb led" , b ut
nothing in "A goat grunted".
+ Matches the preceding item 1 or more times. Equivalent to {1,}.
For example, /a+/ matches the 'a' in "candy" and all the a's in "caaaaaaandy".
Matches the preceding item 0 or 1 time.
For example, /e?le?/ matches the 'el' in "angel" and the 'le' in "angle."
If used immediately after any of the quantifiers *, +, ?, or {}, mak es t he quantif ier no n-
?
greedy (matching the minimum number of times), as opposed to the default, which is greedy
(matching the maximum number of times).
Also used in lookahead assertions, described under (?=), (?!), and (?:) in this table.
(The decimal point) matches any single character except the new line c harac ters: \n \r
. \u2028 or \u2029. ([\s\S] can be used to match any character including new lines.)
For example, /.n/ matches 'an' and 'on' in "nay, an apple is on the tree", but not 'nay'.
Matches x and remembers the match. These are called capturing parentheses.
For example, /(foo)/ matches and remembers 'foo' in "foo bar." The matched subs tring
(x)
can be recalled f rom the resulting array's elements [1], ..., [n] or f rom the
predefined RegExp object's properties $1, ..., $9.
Matches x but does not remember the match. These are called non-capturing parentheses.
(?:x) The matched substring can not be recalled from the resulting array's elements [1], ...,
[n] or f rom the predefined RegExp object's properties $1, ..., $9.
Matches x only if x is followed by y.
For example, /Jack(?=Sprat)/ matches 'Jack' only if it is followed by 'Sprat'.
x(?=y)
/Jack(?=Sprat|Frost)/ matches 'Jack' only if it is f ollowed by 'Sprat' or 'Frost'.
However, neither 'Sprat' nor 'Frost' is part of the match results.
Matches x only if x is not followed by y.
x(?!y) For example, /\d+(?!\.)/ matches a number only if it is not followed by a decimal point.
/\d+(?!\.)/.exec("3.141") matches 141 but not 3.141.
Matches either x or y.
x|y
For example, /green|red/ matches 'green' in "green apple" and 'red' in "red apple."
Where n is a positive integer. Matches exactly n occurrences of the preceding item.
{n} For example, /a{2}/ doesn't match the 'a' in "candy," but it matches all of the a's in
"caandy," and the first two a's in "caaandy."
Where n is a positive integer. Matches at least n occurrences of the preceding item.
{n,} For example, /a{2,} doesn't match the 'a' in "candy", but matches all of the a's in "caandy "
and in "caaaaaaandy."
Where n and m are positive integers. Matches at least n and at most m occurrenc es of t he
preceding item.
{n,m} For example, /a{1,3}/ matches nothing in "cndy", the 'a' in "candy," the f irst t wo a' s in
"caandy," and the f irst three a's in "caaaaaaandy". Notice that when matching
"caaaaaaandy", the match is "aaa", even though the original string had more a's in it.
A character set. Matches any one of the enclosed characters. You can specif y a range
of characters by using a hyphen.
[xyz]
For example, [abcd] is the same as [a-d]. They match the 'b' in "brisket" and t he ' c ' in
"ache".
A negated or complemented character set. That is, it matches anything that is not enclosed
[^xyz] in the brackets. You can specify a range of characters by using a hyphen.
For example, [^abc] is the same as [^a-c]. They initially match ' r' in " brisket " and ' h' in
"chop."
84
LASER ENGINE LANGUAGE REFERENCE
6
The literal notation provides compilation of the regular expression when the expression is ev aluat ed. Us e
literal notation when the regular expression will remain constant. For example, if you use literal not ation t o
construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.
The constructor of the regular expression object, for example, new RegExp("ab+c"), p rovides runt ime
compilation of the regular expression. Use the constructor f unction when you know the regular expres sion
85
PROJECT EDITOR
6
pattern will be changing, or you don't know the pattern and are getting it from another source, such as us er
input.
86
LASER ENGINE LANGUAGE REFERENCE
6
If your regular expression uses the "g" flag, you can use the exec method multiple times to find succ essive
matches in the same string. When you do so, the search starts at the subs tring of str spec if ied by t he
regular expression's lastIndex property. For example, assume you have this script:
var myRe = /ab*/g;
var str = "abbcdefabh";
var myArray;
while ((myArray = myRe.exec(str)) != null)
{
var msg = "Found " + myArray[0] + ". ";
msg += "Next match starts at " + myRe.lastIndex;
print(msg);
}
This script displays the following text:
Found abb. Next match starts at 3
Found ab. Next match starts at 9
function lookup(input)
{
var firstName = /\w+/i.exec(input);
if (!firstName)
{
print(input + " isn't a name!");
return;
}
var count = 0;
for (var i = 0; i < A.length; i++)
{
if (firstName[0].toLowerCase() == A[i].toLowerCase())
count++;
}
var midstring = count == 1 ? " other has ": " others have ";
print("Thanks, " + count + midstring + "the same name!")
87
PROJECT EDITOR
6
RegExp.test([String str])
Executes the search f or a match between a regular expression and a specif ied string.
Returns true or false.
Parameter:
str - The string against which to match the regular expression.
When you want to know whether a pattern is f ound in a string use the test method (similar to
the String.search method); for more information (but slower execution) use the exec method (similar t o
the String.match method).
The f ollowing example prints a message which depends on the success of the test:
function testinput(re, str){
if (re.test(str))
midstring = " contains ";
else
midstring = " does not contain ";
print (str + midstring + re.source);
}
RegExp::toString( );
Returns a string representing the specified object.
The f ollowing example displays the string value of a RegExp object:
myExp = new RegExp("a+b+c");
alert(myExp.toString()); // displays "/a+b+c/"
RegExp::valueOf( )
Returns a string representing the source code of the f unction.
88
LASER ENGINE LANGUAGE REFERENCE
6
• If lastIndex is greater than the length of the string, regexp.test and regexp.exec f ail,
and lastIndex is set to 0.
• If lastIndex is equal to the length of the string and if the regular expression matches t he empt y
string, then the regular expression matches input starting at lastIndex.
• If lastIndex is equal to the length of the string and if the regular expression does no t matc h t he
empty string, then the regular expression mismatches input, and lastIndex is reset to 0.
• Otherwise, lastIndex is set to the next position following the most recent match.
multiline
Ref lects whether or not to search in strings across multiple lines. multiline is a property of an individual
regular expression object..
The value of multiline is true if the "m" flag was used; otherwise, false. The " m" f lag ind ic ates t hat a
multiline input string should be treated as multiple lines. For example, if "m" is used, "^" and "$" c hange
f rom matching at only the start or end of the entire string to the start or end of any line within the string.
You cannot change this property directly.
source
A read-only property that contains the text of the pattern, exc luding t he f orward s las hes. source is a
property of an individual regular expression object.
You cannot change this property directly.
89
PROJECT EDITOR
6
String
A String is a sequence of zero or more Unicode characters. More...
String functions
String String::charAt ( Number pos );
Number String::charCodeAt ( Number pos );
String String::concat ( string2, string3[, ..., stringN] );
Number String::indexOf( String or RegExp pattern, Number pos );
Number String::lastIndexOf ( String or RegExp pattern, Number pos );
String String::match ( RegExp pattern );
String String::replace ( RegExp pattern, String newValue );
Number String::search ( RegExp pattern );
String String::slice ( beginslice[, endSlice]);
String String::split ([separator][, limit]);
String String::substring ( Number startIndex, Number endIndex );
String String::toLowerCase ( );
String String::toString ( );
String String::toUpperCase ( );
String Properties
Number length
Detailed description
A String is a sequence of zero or more Unicode characters. Laser Engine's String class uses the QSt ring
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"
90
LASER ENGINE LANGUAGE REFERENCE
6
The f ollowing example displays characters at different locations in the string "Brave new world":
"ABC".charCodeAt(0) // returns 65
String::concat ( string2, string3[, ..., stringN] );
Combines the text from one or more strings and returns a new string. Changes to the text in o ne s tring do
not af fect the other string.
Parameter:
string2 ... stringN - Strings to concatenate to this string.
s1="Oh "
s2="what a beautiful "
s3="mornin'."
s4=s1.concat(s2,s3) // returns "Oh what a beautiful mornin'."
String::indexOf( String or RegExp pattern, Number pos );
Returns the index of pattern in the string, starting at position pos. If no position is specified, t he f unction
starts at the beginning of the string. If the pattern is not found in the string, -1 is returned.
Parameters:
pattern - A string representing the value to search for.
pos - The location within the calling string to start the search from. It can be any int eger bet ween 0
and the length of the string. The default value is 0.
The f ollowing example uses indexOf to locate a value in the string "Brave new world":
91
PROJECT EDITOR
6
The f ollowing example uses lastIndexOf to locate a value in the string "Brave new world":
The f ollowing example prints a message which depends on the success of the test:
92
LASER ENGINE LANGUAGE REFERENCE
6
The split method returns the new array. When found, separator is removed f rom t he s tring and t he
substrings are returned in an array. If separator is omitted, the array contains one element consisting of t he
entire string.
If separator is a regular expression that contains capturing parentheses, then each time separator is
matched the results (including any undefined results) of the capturing parentheses are spliced into the output
array. However, not all browsers support this capability.
Note:
When the string is empty, split returns an array containing one empty string, rather than an
empty array.
The f ollowing example defines a f unction that splits a string into an array of s t rings using t he s pecif ied
separator. After splitting the string, the function displays messages indicating the original string (b ef ore t he
split), the separator used, the number of elements in the array, and the individual array elements.
function splitString(stringToSplit,separator)
{
var arrayOfStrings = stringToSplit.split(separator);
print('The original string is: "' + stringToSplit + '"');
print('The separator is: "' + separator + '"');
print("The array has " + arrayOfStrings.length + " elements:
");
for (var i=0; i < arrayOfStrings.length; i++)
print(arrayOfStrings[i] + " / ");
}
var tempestString = "Oh brave new world that has such people in
it.";
var monthString = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,
Dec";
splitString(tempestString, space);
splitString(tempestString);
splitString(monthString, comma);
93
PROJECT EDITOR
6
The original string is: "Oh brave new world that has such people
in it."
The separator is: "undefined"
The array has 1 elements: Oh brave new world that has such
people in it. /
The f ollowing example uses substring to display characters from the string "Laser Editor".
// Displays "Light"
print(anyString.substring(0,5));
String::toLowerCase ( );
Returns the value of the string converted to lowercase. toLowerCase does not affect the value of the string
itself .
String::toString ( );
Returns a string representing the specified object.
94
LASER ENGINE LANGUAGE REFERENCE
6
You can ref er to a function's arguments within the function by using the arguments o bjec t. This o bject
contains an entry for each argument passed to the function, the first entry's index starting at 0. For example,
if a f unction is passed three arguments, you can refer to the argument as follows:
arguments[0]
arguments[1]
arguments[2]
The arguments object is not an array. It is similar to an array, but does not have any array properties
except length.
You can use the arguments object if you call a f unction with more arguments than it is formally d eclared t o
accept. This technique is useful for functions that can be passed a variable number of argument s. You c an
use arguments.length to determine the number of arguments passed to the function, and then p rocess
each argument by using the arguments object.
Description
It 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;
}
95
PROJECT EDITOR
6
Infinity
This is the value of any division by zero.
Syntax
var i = 1/0;
In Laser Engine Program, 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.
NaN
NaN means "Not-a-Number", and is used to signify that a value is not a legal number. Use isNaN() f unction
to test a value to see if it is NaN.
undefined
This is the value of a variable that has never been declared, or that has been declared, b ut has not been
assigned a value.
Example:
var i;
// ...
if ( i == undefined ) {
i = 77;
}
In this example, if execution reaches the if statement, and i has no t b een as signed a v alue, it will be
assigned the value 77.
96
LASER ENGINE LANGUAGE REFERENCE
6
connect() isNaN()
disconnect() isFinite()
print() parseFloat()
eval() parseInt()
See also:
• Declaring Functions
connect()
Syntax:
connect(function)
This f unction is used to create signals and slots connections between objects.
It has two f orms, with or without arguments, as it is shown in the following examples:
Note that the f unction is resolved when the connection is made, not when the signal is emitted.
disconnect()
To disconnect from a signal, you invoke the signal's disconnect() f unct ion, pass ing t he f unct ion t o
disconnect as argument:
myQObject.somethingChanged.disconnect(myInterestingFunction);
print()
Syntax:
print( expression )
Prints the expression (applying toString() if necessary) to the output (stderr), followed by a newline.
• Back to the full list of Built-in Functions
97
PROJECT EDITOR
6
eval()
Syntax:
eval( string )
var x = 57;
var y = eval( "40 + x" ); // y == 97
This f unction parses and executes the contents of the string, taking the t ext t o be v alid Las er E ngine
Program.
isFinite()
Syntax:
isFinite( expression )
Returns true if the expression's value is a number that is within range; otherwise returns false.
isNaN()
Syntax:
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"
parseFloat()
Syntax:
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 f ollowed by non-numeric
characters, the value of the number is returned and the trailing characters ignored.
• See also parseInt().
• Back to the full list of Built-in Functions
98
LASER ENGINE LANGUAGE REFERENCE
6
parseInt()
Syntax:
parseInt( string, optBase )
Parses the string and returns the integer that the string represents in the given base optBase, or NaN if
the parse f ails. If the base isn't specified, the base is determined as follows:
Leading and trailing whitespace are ignored. If the string contains a number f ollowed 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
99
PROJECT EDITOR
6
Assignment Operators
These operators are used to assign the value of expressions to variables:
= operator
var variable = expression;
The assignment operator is used to assign the value of an expression to the variable.
+= operator
variable += expression;
This operator adds the value of the expression to the variable. It is the same as:
-= operator
variable -= expression;
This operator subtracts the value of the expression f rom the variable.
*= operator
variable *= expression;
This operator multiplies the value of the expression by the value of the variable.
100
LASER ENGINE LANGUAGE REFERENCE
6
/= operator
variable /= expression;
This operator divides the value of the variable by the value of the expression.
%= operator
variable %= expression;
This operator divides the variable by the expression, and assigns the remainder of the division (whic h
may be 0), to the variable.
&= operator
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.
^= operator
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.
|= operator
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.
<<= operator
variable <<= expression;
This operator performs a bit-wise left shift on the variable by an expression number of bit s. Zeros are
shif ted in from the right.
>>= operator
variable >>= expression;
This operator performs a bit-wise (sign-preserving) right shift on the variable by an expression numb er
of bits.
>>>= operator
variable >>>= expression;
This operator performs a bit-wise (zero-padding) right shift on the variable by an expression number of
bits.
101
PROJECT EDITOR
6
Arithmetic Operators
+ operator * operator
++ operator / operator
- operator % operator
-- operator
+ operator
operand1 + operand2
This operator returns the result of adding the two operands (operand1 and operand2).
++ 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.
- operator
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 f irst operand (operand1).
The unary negation version of this operator returns the result of negating (changing the sign) of its operand.
-- operator
--operand; // pre-decrement
operand--; // post-decrement
The pre-decrement version of this operator decrements the operand, and ret urns t he value of t he (now
decremented) operand.
The post-decremented version of this operator returns the value of the operand, and then d ecrement s
the operand.
* operator
operand1 * operand2
This operator returns the result of multiplying the two operands (operand1 and operand2).
102
LASER ENGINE LANGUAGE REFERENCE
6
/ operator
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. (See Inf inity).
% operator
operand1 % operand2
This operator returns the integer remainder (which may be 0) f rom the division of operand1 by operand2.
String Operators
These operators provide string functions using operators. Many other string functions are av ailable. (See
also String built-in type).
Logical Operators
These operators are used to evaluate whether their operands are true or false in terms of the o perator
(f or unary operators) and in terms of each other (f or 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.
103
PROJECT EDITOR
6
Comparison Operators
< operand1 < Returns true if operand1 is less than operand2; otherwise
operand2 returns false.
<= operand1 <= Returns true if operand1 is less than or equal to operand2; otherwise
operand2 returns false.
Bit-wise operators
These operators perform their operations on binary representations, but they return standard Las er E ngine
Program numerical values.
104
LASER ENGINE LANGUAGE REFERENCE
6
Special Operators
The f ollowing special operators are available:
?: operator
expression ? resultIfTrue : resultIfFalse
This operator evaluates its first operand, the expression. If the expression is true, t he v alue of t he
second operand (resultIfTrue) is returned; otherwise the value of the third operand (resultIfFalse) is
returned.
, operator
expression1, expression2
This operator evaluates its first and second operand (expression1 and expression2), and ret urns t he
value of the second operand (expression2).
The comma operator can be subtle, and is best reserved only for use in argument lists.
function operator
var variable = function( optArguments ) { Statements }
This operator is used to create anonymous functions. Once assigned, the variable is used like any ot her
f unction 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 s t ill be p assed and will b e
available using the arguments list. (See Arguments variable).
The Laser Engine Program 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 f or each call to make_counter(), the anonymous function t hat is ret urned has it s own c opy
of current (initialized to the initialValue), which is incremented independently of any other anonymous
f unction's current. It is this capturing of context that makes the function that is returned a closure.
See also Declaring Functions.
105
PROJECT EDITOR
6
in operator
property in Object
Returns true if the given Object has the given property; otherwise returns false.
instanceof operator
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.
new operator
var instance = new Type( optArguments );
This f unction 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 t ypes, one of t he
library types, or a user-defined type.
Example:
var circle = new Circle( x, y );
var file = new File();
this operator
this.property
The this operator may only be used within a f unction that is defined within a class or f orm, i.e. a member
f unction. Within the scope of the function this is a ref erence to the particular instance (object) of the class's
type. (See also Declaring Functions and Declaring Classes).
Example:
function Car(brand) {
this.brand = brand;
}
Car.prototype.getBrand = function() {
return this.brand;
}
typeof operator
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"
Functions and built-in objects have a typeof of "function".
106
NOTE:
107