Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Project Editor User Guide

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Project Editor User Guide

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

USER GUIDE

> Project Editor


Datalogic S.r.l.
Via S. Vitalino 13
40012 – Calderara di Reno
Italy

Barcode Reference User Guide

Ed.: 09/2017

Helpful links at www.datalogic.com: Contact Us, Terms and Conditions, Support.

© 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

Revision Date Number of added or edited pages

10/2012 31/10/2012 Release

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

2. GETTING STARTED WITH PROJECT EDITOR ........................................................................... 7


2.1 ABOUT PROJECT EDITOR ............................................................................................... 8
2.2 WORK ENVIRONMENT OVERVIEW................................................................................... 9
2.2.1 Work environment components: ................................................................................. 10

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

4. OPENING, SAVING, AND DELETING PROJECTS..................................................................... 22


4.1 OPENING A PROJECT ................................................................................................... 23
4.2 SAVING A PROJECT...................................................................................................... 24
4.2.1 Saving a project locally ............................................................................................. 24
4.2.2 Saving a project to the device .................................................................................... 24
4.3 MANAGING FILES ON THE DEVICE ................................................................................ 25
4.3.1 Opening a project f rom a device................................................................................. 25
4.3.2 Saving a project as the default project ......................................................................... 25
4.3.3 Deleting a project from the device............................................................................... 25

5. SENDING PROJECTS TO MARKING....................................................................................... 26


5.1 CONNECTING TO THE DEVICE ...................................................................................... 27
5.2 RUNNING A PROJECT ................................................................................................... 28
5.2.1 Manual Mode vs. Auto Mode ..................................................................................... 28
5.2.2 Executing the marking operation ................................................................................ 28
5.3 TESTING A PROJECT .................................................................................................... 29

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

1.1 ABOUT THIS HELP SYSTEM


This Help System is designed for developers who will be using Project Editor to write and manage programs
so as to customize and automate laser engraving operations.

Project Editor is integrated into Laser Editor.

1.1.1 Using the Help System:


• To access the whole contents, choose Help > Help f rom the Project Editor's menu bar, or
press F1 in the main screen of the application.
• To use the context-sensitive Help: press F1 (or the ? button in the title bar) to open dialog or window
level Help.

1.1.2 Contents of the Help:


In particular, the Help is organized into the following main topics:

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

2. GETTING STARTED WITH PROJECT EDITOR

This chapter is organized into the following sections:

Topic What you will learn


About Project Editor Scope and overview of Project Editor.
Work environment overview Overview on how the work environment is organized.

7
PROJECT EDITOR
2

2.1 ABOUT PROJECT EDITOR


Project Editor is a programs editor integrated into Laser Editor. It has a friendly us er int erf ace, adv anc ed
debugging functions, and is provided with samples programs and reference material. Developers c an us e
this tool to write and manage programs so as to interact with the laser system.

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.

By creating your own programs with Project Editor you can:


• control the marking process
• f ully customize your layout
• interact with users and with other programs or devices
• automate procedures and update the layout's contents at runtime

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

2.2 WORK ENVIRONMENT OVERVIEW


This section provides an overview of the Project Editor work environment.

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

2.2.1 Work environment components:


Area Description

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

This chapter is organized into the following sections:


• Editor configuration
• Creating a project
• Adding files to the project
• Working with Source files
• About Formatters

11
PROJECT EDITOR
3

3.1 EDITOR CONFIGURATION


You can customize Project Editor in terms of syntax formatting of the source files during editing.

To customize the editor:


1. From the Project Editor's menu bar, choose Edit > Configuration. The Preferences d ialog b ox is
displayed showing the current settings:

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

3.2 CREATING A PROJECT


About Projects
The Project is a program with a .xqs extension that works as a "container" for the files that are used t o run
the application. In particular a project is composed by Source files, that is, the files that cont ain t he c ode,
and Resource files, that is, any image file, database file, Word or Excel documents, and s o fort h t hat are
required to run the program. (See Adding files to the project).

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.

Figure Project Files pane

In particular, the Project Files pane allows you to:

• 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.

To create a new project:


1. Do one of the following:

o Click the New Project button on the toolbar.


o From the menu bar, choose File > New Project.
2. A new def ault project is created, named Untitled, which contains a def ault source f ile
named main.qs. You can use the default project as the basis for your application.
3. If you want, rename the project or the file as required: Right-click the name, choose Rename fi l e,
and then enter the new name.
4. Enter the code in the source file as required.
5. Add or import any Source or Resource files you need by doing one of the following:
o Right-click the Project folder and choose the option you want.
o Choose a command from the File menu.
6. Save your project as required. (See Saving a project)

To install a project deployed from somebody else:


According to the format the project comes to you (flat files or zipped archive), do the f ollowing st eps f rom
point "2" or "1" respectively:
1. Unzip the archive in a local directory.
2. Follow the steps for opening a project.
3. Follow the steps for saving a project to the device.

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

3.3 ADDING FILES TO THE PROJECT


Typically, you create (or open) a Project and then you add the files that are us ed t o run t he p rogram. In
particular:
• Source files, that is, the files that contain the code. A source file has a . qs ex t ens ion. Y ou can
directly enter the code into the program editor area of Project Editor, or you can import an ex is ting
f ile.
• Resource files, that is, any image file, icons, database file, Word or Excel documents, and so f ort h
that are required by the program at runtime, as well as XML files that are used for marking on plastic
cards. You can import any of these files into your project.

(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

3.3.1 Creating a new source file

To create a new file:


1. Create the project (See Creating a project) and then do one of the following:
o From the menu bar, choose File > New source file.
o In the Project Files pane, right-click the Source Files folder or an existing s ource f ile and
then choose New source file from the shortcut menu.

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.

To print a source file:


1. Open the f ile to be printed. (If no file is opened, the command is disabled).
2. From the Project Editor menu bar, choose File > Print source file.
3. Choose the printer and click OK.

3.3.2 Importing source or resource files into a project


You can import both source and resource files. The f iles that you import are ad ded t o t he c orresponding
f older into the Project Files pane.

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).

To import a source file:


You can import an existing source file for further editing.
1. Do one of the following:
o From the menu bar, choose File > Import source file.
o In the Project Files pane, right-click the Source Files folder or an existing s ource f ile and
then choose Import source file from the shortcut menu.
2. In the Import file window that is displayed, browse to locate the .qs file and click Open.
Note that the f ile is added under the Source files folder in the Project Files pane.

To import a resource file


You might import image files, icons, database file, Word or Excel documents, as well as XML files.
1. Do one of the following:
o From the menu bar, choose File > Import file.
o In the Project Files pane, right-click the Resource Files folder or an existing res ource f ile
and then choose Import file from the shortcut menu.
2. In the Import file window that is displayed, browse to locate the required file and then click Open.

Note that the f ile is added under the Resource files folder in the Project Files pane.

16
MANAGING PROJECTS
3

3.4 WORKING WITH SOURCE FILES


You can easily manage or edit source files by using the menu bar, the toolbar, or by right-clicking t he files
into the Project Files pane.

For further information:


• Copying, cutting, and pasting text
• Searching or replacing text
• Renaming or deleting files
• Exporting source files

17
PROJECT EDITOR
3

3.4.1 Copying, cutting, and pasting text


When a source f ile is displayed in the program editor area, you can use the menu bar o the toolbar to
perf orm common operations.

To copy, cut, and paste text:


1. Select the text in the source file (or choose File > Select all to select all the code).

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.

2. Use the Undo/Redo commands to reverse the changes.

18
MANAGING PROJECTS
3

3.4.2 Searching or replacing text


When a source file is displayed in the program editor area, you can use the searc h f unctions t o loc ate or
replace text.

To search the text:


1. From the Search menu, choose the appropriate command (Find, Find Next, or Find Previous).
2. In the window that is displayed, specify the search criteria and then click Find.

To search and replace the text:


1. From the Search menu, choose Replace.
2. In the window that is displayed, enter the text to be found and text for the replacement.
3. Specify the search criteria and then click Replace or Replace all.

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

3.4.3 Renaming or deleting files


You might rename or remove both source and resource files.

To rename a source or resource file:


1. In the Project Files list, right-click the file (not the folder) you want to rename.
2. From the shortcut menu, choose Rename File, enter a new name in the window t hat is d is played
and then click OK.

To delete a source or resource file:


1. In the Project Files list, right-click the file (not the folder) you want to delete.
2. From the shortcut menu, choose Delete File.
3. Answer Yes in the window that is displayed.

3.4.4 Exporting source files


You might export source files so as to be used for other applications. When you export a f ile, a copy of it is
saved as a .qs file in another location and the original is kept into your project.

To export a source file:


1. In the Project Files pane, right-click the source file (not the folder) y ou want t o export and t hen
choose Export file from the shortcut menu.
2. In the Export file window that is displayed, select the folder you want to save t he .qs f ile in, and
then click on Save.

20
MANAGING PROJECTS
3

3.5 ABOUT FORMATTERS


Formatters are source f iles that are supplied with Project Editor. These f iles can be used as f unctions
libraries.

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

4. OPENING, SAVING, AND DELETING PROJECTS

This chapter is organized into the following sections:


• Opening a project
• Saving a project
• Managing files on the device

22
MANAGING PROJECTS
4

4.1 OPENING A PROJECT


You can open projects that you have previously saved f or f urther editing, or f or sending them to the
engraver.

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

4.2 SAVING A PROJECT


You can save a project either locally, or to a device so that it is then sent to the engraver through an
automated procedure. Furthermore, you can save a project to a device as the default project (see S aving a
project as the default project).

4.2.1 Saving a project locally


The f ollowing procedure allows saving a project with a .xqs extension (Laser Project file) on y our d is k, f or
later use or editing.

To save the project:


1. To save a new, unnamed project:

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.

2. To save a copy of an existing project:


o Choose File > Save Project as.
o In the Save project as window that is displayed, either go to the desired location or keep the
def ault one.
o In the File name box, type a new name for the project and click Save.

4.2.2 Saving a project to the device


The f ollowing procedure allows saving a project to the device to which you are connected.
The projects are saved into the folder that is shared with the Laser Engine. They will be sent to the engraver
in an automated way.

To save the project to a device:


1. To save a new, unnamed project:
o From the Project Editor menu bar, choose File > Save project to devi ce. The p roject is
saved automatically to the current device.
2. To save a copy of an existing project with a specific name:
o From the Project Editor menu bar, choose File > Save project to device as.
o In the Project name window that is displayed, enter a new name f or the project and
click OK.

24
MANAGING PROJECTS
4

4.3 MANAGING FILES ON THE DEVICE


You can open, save, or delete projects to and from the device to which you are connected. Furthermore, you
can save a project as the default.

In order to interact to a device you must be connected with it (see Connecting to the device).

4.3.1 Opening a project from a device


You can open a project that has been previously saved to a device for edit or test operations, before sending
it to the engraver.

To open a project from a device:


1. From the Project Editor menu bar, choose File > Open project from 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 open and click OK.

4.3.2 Saving a project as the default project


When your project is ready, you can save it to the current device as the default. This way, this project will be
automatically executed whenever the Auto Mode (default mode) is activated, that is, on any system boot.

To save a project as the default:


1. From the Project Editor menu bar, choose File > Save device default project.
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 as the default and click OK.

4.3.3 Deleting a project from the device


You can delete a project that has been saved 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

5. SENDING PROJECTS TO MARKING

This chapter is organized into the f ollowing sections:


• Connecting to the device
• Running a project
• Testing a project

26
CONNECTING TO DEVICE
5

5.1 CONNECTING TO THE DEVICE


The laser device that you will use for marking your layouts can be either local, in the case of a s t and-alone
marking solution, or remote, in the case of a Supervisor unattended marking solution, typically on a
production line.

In both cases, you can use the File menu to connect to the device.

To connect to the device:


1. From Project Editor menu bar, choose File > Connect to device.
2. In the Connect to device device window that is displayed, choose the device you want t o c onnect
to.

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

5.2 RUNNING A PROJECT

When you are ready with your project (see Creating a project), you can run the program in two ways:

• In Manual Mode - By pressing F5 (or clicking Run Project).


• In Auto Mode - By saving the project to the device and executing it at the device level by activating
the Auto Mode. (See Saving a project).

5.2.1 Manual Mode vs. Auto Mode


In Auto Mode, programs are executed by the Laser Engine; this means that the currently s elect ed d ef ault
project is executed.

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.

To switch to the Manual Mode:


1. From the Project Editor menu bar, choose File > Switch to Manual Mode.
2. Select either the device or the simulator and then run the project.

5.2.2 Executing the marking operation


Attention:
When you execute a project (that is, when you press Run Project), all the sourc e and res ource
f iles that compose it are copied to the device before being executed. Note that any f ile with t he
same name will be overwritten.

To send the project to the engraver:


1. Be sure that you are in Manual Mode.
2. Do one of the following:

o Press F5 or click on Run Project on the toolbar.


o Choose Project > Run project f rom the menu bar).
3. Note that in the Output pane of the Project Editor's window, the results of the operation are
displayed. In the example here below the message says that the program has been loaded:

4. To stop the execution, click Stop Project.

28
CONNECTING TO DEVICE
5

To save a project to the device for next marking:


From the Project Editor menu bar, do one of the following:
• To save the project, choose File > Save Project to Device or Save Project to Device As. The
project will be sent to the engraver in an automated way. (For furt her inf ormation, s ee S aving a
project to the device).
• To save the project as the def ault, choose File > Save device default project. (For f urther
inf ormation, see Saving a project as the default project).

5.3 TESTING A PROJECT

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).

To test your program:


1. Be sure that you have activated the Manual Mode. To activate it, from the menu bar, choose Fil e >
Switch to Manual Mode.
Note: This is a toggle command: if the Manual Mode is activated, the command is To Aut o Mode,
and vice versa.

2. Press F5 (or click Run Project).

3. To stop the project, click Stop Project.

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

6. LASER ENGINE LANGUAGE REFERENCE

About this reference


This language ref erence describes the language f eatures provided by Laser Engine Program for
Applications.

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.

Readers are assumed to have a basic understanding of programming.

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

6.1 IDENTIFIERS AND RESERVED WORDS

6.1.1 What are identifiers


Identif iers are the names for things that you get to make up.

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

6.1.2 Reserved words (Keywords)


Laser Engine Program reserves some words which are valid identifiers for its own use.

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

6.2 COMMENTING THE CODE


Laser Engine Program for Applications supports the same commenting syntax as C++.

One line comments may appear on a line of their own, or after the statements on a line. Multi-line comments
may appear anywhere.
// A one line comment.

/*
A multi-line
comment.
*/

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

6.3.1 Declaring Functions


A f unction definition consists of the function keyword, followed by:
• The name of the function.
• A list of arguments to the function, enclosed in parentheses and separated by commas.
• The Laser Engine Program statements that define the function, enclosed in c urly braces , { }. The
statements in a f unction can include calls to other functions defined in the current application.

For example, the following code defines a simple function named square:

function square(number) {
return number * number;
}

6.3.2 Declaring Classes


A class is not defined explicitly; there is no class keyword. Instead, you def ine a new c lass by d ef ining
a constructor function that will initialize new objects.

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;
}

// set the prototype to be an instance of the base class


Employee.prototype = new Person();

// 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 e = new Employee("Johnny Bravo", 5000000);


print(e instanceof Employee); // true
print(e instanceof Person); // true
print(e instanceof Object); // true
print(e instanceof Array); // false

6.3.3 Declaring Variables


Variables are declared using the var keyword:

var a; // undefined
var c = "foliage"; // the string "foliage"
x = 1; // global variable

If a variable is assigned to without being declared, it is automatically declared as a global variable.

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

6.3.4 Declaring Constants


Constants are declared using the const keyword:

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

6.4 CONTROL STATEMENTS


The f low--of--control in Laser Engine Program is controlled by control statements.

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:

Table 1 Statements list


Statement Description
Terminates the current loop, switch, or label statement and transfers program c ontrol t o t he
break
statement following the terminated statement.
const Declares a global constant and initializes it to a value.
This keyword is used within the context of a for, while or do loop. Terminates execut ion
continue of the statements in the current iteration of the current or labelled loop, and continues
execution of the loop with the next iteration.
Creates a loop that consists of three optional express ions , enc los ed in parent heses and
f or
separated by semicolons, followed by a statement executed in the loop.
f unction Declares a f unction.
Executes a statement if a specif ied condition is true. If the condition is f alse, another
if ...else
statement can be executed.
label Provides an identifier for a statement (continue) and refers to it elsewhere in a program.
return Specifies the value to be returned by a function.
Evaluates an expression, matching the expression's value to a case label, and executes
switch
statements associated with that case.
throw Throws a user-def ined exception.
try...catch Marks a block of statements to try, and specifies a response, should an exception be thrown.
var Declares a variable, optionally initializing it to a value.
Creates a loop that executes a specified statement as long as the test condition evaluat es t o
while
true. The statement is executed after evaluating the condition.
with Extends the scope chain for a statement.

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

Using continue with while

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;
}

Using continue with a label


In the f ollowing example, a statement labeled checkiandj contains a statement labeled checkj.
If continue is encountered, the program continues at the top of the checkj statement. Each
time continue is encountered, checkj reiterates until its condition returns false. When false is ret urned,
the remainder of the checkiandjstatement is completed.

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:

for (var i = 0; i < 9; i++) {


n += i;
myfunc(n);
}

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.

function calc_sales(units_a, units_b, units_c) {


return units_a*79 + units_b * 129 + units_c * 699;
}

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:

var b = new Boolean(false);


if (b) // this condition evaluates to true

Examples

Using if ... else


if (cipher_char == from_char) {
result = result + to_char;
x++;
} else
result = result + clear_char;

Assignment within the conditional expression


It is advisable to not use simple assignments in a conditional expression, because the as signment can b e
conf used with equality when glancing over the code. For example, do not use the following code:

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:

throw "Error2"; // generates an exception with a string value


throw 42; // generates an exception with the value 42
throw true; // generates an exception with the value true

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

Another example of throwing an object


The f ollowing example tests an input string for a U.S. zip code. If t he zip code us es an inv alid f ormat,
the throw statement throws an exception by creating an object of type ZipCodeFormatException.

/*
* 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.
*/

var ZIPCODE_INVALID = -1;


var ZIPCODE_UNKNOWN_ERROR = -2;

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;
}

a = verifyZipCode(95060); // returns 95060


b = verifyZipCode(9560;) // returns -1
c = verifyZipCode("a"); // returns -1
d = verifyZipCode("95060"); // returns 95060
e = verifyZipCode("95060 1234"); // returns 95060 1234

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

Unconditional catch clause


When a single, unconditional catch clause is used, the catch block is entered when any ex cept ion is
thrown. For example, when the exception occurs in the following code, control transfers to the catch clause.

try {
throw "myException"; // generates an exception
}
catch (e) {
// statements to handle any exceptions
logMyErrors(e); // pass exception object to error handler
}

The exception identifier


When an exception is thrown in the try block, exception_var (e.g. the e in catch (e)) holds the value
specified by the throw statement. You can use this identifier to get information about the exception that was
thrown.

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.

The finally clause


The finally clause contains statements to execute after the try block and catch clause(s) ex ecut e but
bef ore the statements following the try statement. The finally clause executes regardless of whet her or
not an exception is thrown. If an exception is thrown, the statements in the finally clause execute ev en if
no catchclause handles the exception.

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.

var num_hits = 0, cust_no = 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.

Performance Pro & Con


• Pro: 'with' can help reduce file size by reducing the need to repeat a lengthy object reference without
perf ormance penalty. The scope chain change required by 'with' is not computationally ex pensive.
Use of 'with' will relieve the interpreter of parsing repeated object references. Note, however, that in
many cases this benefit can be achieved by using a temporary variable to store a ref erence t o t he
desired object.
• Con: 'with' forces the specified object to be searched first for all unqualified name lookups. Therefore
all identifiers that match formal function argument and declared local variable names will be f ound
more slowly in a 'with' block. Where performance is important, 'with' would lik ely only be us ed t o
encompass code blocks that do not use function argument and declared local variable identifiers.

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

6.5 CLASSES AND METHODS (MEMBER FUNCTIONS)


Laser Engine Program is a fully object oriented language.
A class's constructor is the function which has the same (case-sensit iv e) name as t he c las s it self . The
constructor should not contain an explicit return statement; it will return an object of its type automatically.
Laser Engine Program does not have a destructor f unction (a f unction that is called when the class is
destroyed), for a class.
The class's member variables are declared with var (see Declaring Variables), and it s member f unct ions
(methods) with function (see Declaring Functions).
The object instance itself is referred to using the this operator. Inside a member function of a class, member
variables and member functions can be accessed with an explicit this (e.g. this.x = posx;). This is no t
required, but can sometimes help to increase visibility.
Laser Engine Program supports single inheritance, and if a class inherits from another class, the constructor
of the superclass constructor can be called with super().

For further information:


• Qualif ied Names
• Class Properties
• Declaring Classes

6.5.1 Qualified Names


When you declare an object of a particular type, the object itself becomes, in ef f ect , a namespac e. For
example, in Laser Engine Program there is a f unction called Math.sin(). If you want to have
a sin() f unction in your own class that would not be a problem, because objects of your class would c all t he
f unction using theobject.function() syntax. The period is used to distinguish the namespace a
particular identifier belongs to.

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.

6.5.2 Class Properties


A property is an undeclared variable that can be written to and accessed if the class supports properties. The
classes supporting properties are the application objects and the classes provided by the object and wrapper
f actories.

var obj = new Object


object.myProperty = 100;

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

6.6 NATIVE AND BUILT-IN OBJECTS


Ref erence documentation for native and built-in objects is organized as follows:

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

6.6.1 Native Objects


Native objects are supplied by the Laser Engine Program implementation. Some native objects are b uilt -in;
others may be constructed during the course of execution of a Laser Engine Program.

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

In this section the following objects are described:


• Math
• Array
• Boolean
• Date
• Number
• RegExp
• String

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

Math functions documentation


Math::abs ( Number number );
Returns the absolute value of the given number.

The equivalent of:


x = x < 0 ? -x : x;

var x = -99;
var y = 99;
with ( Math ) {
x = abs( x );
y = abs( y );
}
if ( x == y )
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.

The f ollowing shows an example:

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.

The f ollowing shows an example:

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

Math::exp ( Number number );


Returns Math.E raised to the power of the given number.
Math::floor ( Number number );
If the number is an integer, it returns the number. If the number is a floating point v alue, it ret urns t he
greatest integer less than the number.
Math::log ( Number number );
If the number is > 0, it returns the natural logarithm of the given number. If t he number is 0, it ret urns
Inf inity. If the number is < 0, it returns NaN.
Math::max ( Number number1, Number number2 );
Returns the largest of number1 and number2.
Math::min ( Number number1, Number number2 );
Returns the smallest of number1 and number2.
Math::pow ( Number number, Number power);
Returns the value of the number raised to the power.
Math::random ( );
Returns a pseudo-random floating point number between 0 and 1. Pseudo random numbers are no t t ruly
random, but may be adequate for some applications, for example, games and simple simulations.
Math::round ( Number number );
Returns the number rounded to the nearest integer. If the f ractional part of the number is >= 0.5, the
number is rounded up; otherwise it is rounded down.
Math::sin ( Number number );
Returns the sine of the given number. The value will be in the range -1..1.
Math::sqrt ( Number number );
If the number is >= 0, it returns the square root. If the number is < 0, it returns NaN.
Math::tan ( Number number );
Returns the tangent of the given number.

62
LASER ENGINE LANGUAGE REFERENCE
6

Math properties documentation

All the Math properties are read-only constants.

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.

Array constructor documentation


Arrays can be constructed from array literals or using the new operator:
var mammals = [ "human", "dolphin", "elephant", "monkey" ];
var plants = new Array( "flower", "tree", "shrub" );
var things = [];
for ( i = 0; i < mammals.length; i++ ) {
things[i] = new Array( 2 );
things[i][0] = mammals[i];
things[i][1] = plants[i];
}
Arrays can be initialized with a size, but with all items undefined:
var a = new Array( 10 ); // 10 items

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:

var names = [];


names["first"] = "John";
names["last"] = "Doe";
var firstName = names["first"];
var lastName = names["last"];

names["address"] = "Somewhere street 2";


names.phoneNumber = "+0123456789";
var address = names.address;
var phoneNumber = names["phoneNumber"];

Array functions documentation


Array::concat ( Array a1, Array a2 ... aN );
Concatenates the array with one or more other arrays in the given order, and returns a single array.
Parameter:
a1 ... aN - Arrays and/or values to concatenate to the resulting array.
var x = new Array( "a", "b", "c" );
var y = x.concat( [ "d", "e" ], [ 90, 100 ] );
// y == [ "a", "b", "c", "d", "e", 90, 100 ]
Array::join ( String optSeparator );
Joins all the items of an array together, separated by commas, or by the specified optSeparator.
var x = new Array( "a", "b", "c" );
var y = x.join(); // y == "a,b,c"
var z = x.join( " * " ); // y == "a * b * c"
Array::pop ( );
Pops (that is, removes) the top-most (right-most) item off the array and returns it.
var x = new Array( "a", "b", "c" );
var y = x.pop(); // y == "c" x == [ "a", "b" ]

65
PROJECT EDITOR
6

Array::push ( item1, optItem2, ... optItemN );


Pushes (that is, inserts) the given items onto the top (right) end of the array. The f unction ret urns t he new
length of the array.
Parameter:
item1 ... optItemN - The items to add to the array.
var x = new Array( "a", "b", "c" );
x.push( 121 ); // x == [ "a", "b", "c", 121 ]
Array::reverse ( );
Reverses the items in the array.
var x = new Array( "a", "b", "c", "d" );
x.reverse(); // x == [ "d", "c", "b", "a" ]
Array::shift ( );
Shif ts (that is, removes) the bottom-most (left-most) item off the array and returns it.
var x = new Array( "a", "b", "c" );
var y = x.shift(); // y == "a" x == [ "b", "c" ]
Array::slice ( Number startIndex, Number optEndIndex );
Extracts a slice of the array from the item with the given starting index to the item before t he it em with t he
given ending index, optEndIndex.
Parameters:
startIndex - Zero-based index at which to begin extraction.
optEndIndex - Zero-based index at which to end extraction. slice extracts up to b ut no t inc luding
end.
If no ending index is given, all items from the starting index onward are sliced.
var x = new Array( "a", "b", "c", "d" );
var y = x.slice( 1, 3 ); // y == [ "b", "c" ]
var z = x.slice( 2 ); // z == [ "c", "d" ]
Array::sort ( Function optComparisonFunction );
Sorts the items in the array using string comparison.
Parameter:
optComparisonFunction - Specifies a function that defines the sort order. If omitted, the array is sort ed
lexicographically (in dictionary order) according to the string conversion of each element.

For customized sorting, pass the sort() function a comparison function, optComparisonFunction, t hat
has the f ollowing signature and behavior:

var x = new Array( "d", "x", "a", "c" );


x.sort(); // x == [ "a", "c", "d", "x" ]
function comparisonFunction( a, b ) // signature

The f unction above must return an integer as follows:


• -1 if a < b
• 0 if a == b
• 1 if a > b

66
LASER ENGINE LANGUAGE REFERENCE
6

The f ollowing is an example:

function numerically( a, b ) { return a < b ? -1 : a > b ? 1 :


0; }
var x = new Array( 8, 90, 1, 4, 843, 221 );
x.sort( numerically ); // x == [ 1, 4, 8, 90, 221, 843 ]
Array::splice ( Number startIndex, Number replacementCount, optItem1, ... optItemN );
Splices items into the array and out of the array.
Parameters
startIndex - The index at which to start changing the array.
replacementCount - The number of items that are to be replaced.
optItem1 ... optItemN - The items to be inserted.
Make the second argument 0 if you are simply inserting items.If you are simply deleting items, t he s econd
argument must be > 0 (that is, the number of items to delete), and there must be no new items given.
var x = new Array( "a", "b", "c", "d" );

// 2nd argument 0, plus new items ==> insertion


x.splice( 1, 0, "X", "Y" );
// x == [ "a", "X", "Y", "b", "c", "d" ]

// 2nd argument > 0, and no items ==> deletion


x.splice( 2, 1 );
// x == [ "a", "X", "b", "c", "d" ]

// 2nd argument > 0, plus new items ==> replacement


x.splice( 3, 2, "Z" );
// x == [ "a", "X", "b", "Z" ]
Array::toString ( );
Joins all the items of an array together, separated by commas.
This f unction is used when the array is used in the context of a string concatenation or is used as a t ex t
value, e.g. for printing. Use join if you want to use your own separator.
See also:
Array::join ( String optSeparator );
var x = new Array( "a", "b", "c" );
var y = x.toString(); // y == "a,b,c"
var z = x.join(); // y == "a,b,c"
Array::unshift ( String expression, optExpression1, ... optExpressionN );
Unshif ts (that is, inserts) the given items at the bottom (left) end of the array and returns the new leng th of
the array.
Parameter:
expression ... optExpressionN - The items to add to the array.
var x = new Array( "a", "b", "c" );
x.unshift( 121 ); // x == [ 121, "a", "b", "c" ]

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.

Boolean functions documentation


Boolean::toString ( );
Returns a string representing the specified Boolean object.
Laser Engine Program calls the toString method automatically when a Boolean is to be represented as a
text value or when a Boolean is referred to in a string concatenation. For Boolean objects and v alues, t he
built-in toString method returns the string "true" or "false" depending on the value of the boolean object.

In the f ollowing code, flag.toString returns "true".

var flag = new Boolean(true)


var myVar=flag.toString()
Boolean::valueOf ( );
Returns the primitive value of a Boolean object or literal Boolean as a Boolean data type.
x = new Boolean();
myVar = x.valueOf() //assigns false to myVar

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 constructor documentation


Dates can be constructed with no arguments, in which case the value is the date and time at the moment of
construction using local time. A single integer argument is taken as the number of milliseconds since
midnight on the 1st January 1970.

Date()
Date( milliseconds )
Date( year, month, day, optHour, optMinutes, optSeconds,
optMilliseconds )

var today = new Date();


var d = new Date( 1234567 );
var date = new Date( 1994, 4, 21 );
var moment = new Date( 1968, 5, 11, 23, 55, 30 );

Static Date functions documentation


Date::parse ( String dateString );
This is a static function that parses a string, dateString, which represents a particular dat e and t ime. It
returns the number of milliseconds since midnight on the 1st January 1970. The string mus t b e in t he IS O
8601 extended format:
YYYY-MM-DD or with time YYYY-MM-DDTHH:MM:SS.
var d = new Date( Date.parse( "1976-01-25T22:30:00" ) );
d = Date.parse( "1976-01-25T22:30:00" );
Date::UTC (year, month[, date[, hrs[, min[, sec[, ms]]]]] )
Accepts the same parameters as the longest form of the constructor, and returns the number of milliseconds
in a Date object since January 1, 1970, 00:00:00, universal time.
Parameters
year - A year af ter 1900.
month - An integer between 0 and 11 representing the month.
date - An integer between 1 and 31 representing the day of the month.
hrs - An integer between 0 and 23 representing the hours.
min - An integer between 0 and 59 representing the minutes.
sec - An integer between 0 and 59 representing the seconds.
ms - An integer between 0 and 999 representing the milliseconds.

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.

• Date.UTC uses universal time instead of the local time.


• Date.UTC returns a time value as a number instead of creating a Date object.

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:

gmtDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0));

Date functions documentation


Date::getDate ( );
Returns the day of the month using local time. The value is always in the range 1..31.
var d = new Date( 1975, 12, 25 );
var x = d.getDate(); // x == 25
Date::getDay ( );
Returns the day of the week using local time. The value is always in the range 1..7, with the week
considered to begin on Monday.
var d = new Date( 1975, 12, 25, 22, 30, 15 );
var x = d.getDay(); // x == 4

The f ollowing shows an example:


var IndexToDay = [ "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sun" ];
var d = new Date( 1975, 12, 28 );
System.println( IndexToDay[ d.getDay() - 1 ] ); // Prints "Sun"
Date::getFullYear ( );
Returns the year of the specified date according to local time.
The value returned by getFullYear is an absolute number. For dates between the years 1000 and
9999, getFullYear returns a four-digit number, for example, 1995. Use this function to make sure a y ear
is compliant with years after 2000.

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

The f ollowing shows an example:

var IndexToMonth = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",


"Jul",
"Aug", "Sep", "Oct", "Nov",
"Dec" ];
var d = new Date( 1975, 12, 25 );
System.println( IndexToMonth[ d.getMonth() - 1] ); // Prints
"Dec"
Date::getSeconds ( );
Returns the seconds component of the date using local time. The value is always in the range 0..59. In the
example x is 0 because no seconds were specified, and the default for unspecified components of the t ime
is 0.
var d = new Date( 1975, 12, 25, 22, 30 );
var x = d.getSeconds(); // x == 0
Date::getTime ( );
Returns the number of milliseconds since midnight on the 1st January 1970 using local time.
var d = new Date( 1975, 12, 25, 22, 30 );
var x = d.getTime(); // x == 1.91457e+11
Date::getTimezoneOffset ( );
Returns the time-zone offset in minutes for the current locale.
The time-zone offset is the minutes in difference, the Greenwich Mean Time (GMT) is relative to y our loc al
time. For example, if your time zone is GMT+10, -600 will be returned. Daylight savings time prevents t his
value f rom being a constant.
x = new Date()
currentTimeZoneOffsetInHours = x.getTimezoneOffset()/60
Date::setDate ( Number dayOfTheMonth );
Sets the day of the month to the specified dayOfTheMonth in local time.
var d = new Date( 1975, 12, 25, 22, 30 );
d.setDate( 30 ); // d == 1975-12-30T22:30:00
Date::setFullYear ( yearValue[, monthValue[, dayValue]] );
Sets the f ull year for a specified date according to local time.
Parameters
yearValue - An integer specifying the numeric value of the year, for example, 1995

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

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.toTimeString()); // prints 14:39:07 GMT-0600 (PDT)
Date::toLocaleString ( );
Converts a date to a string, using the operating system's locale's conventions.

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

today = new Date(95,11,18,17,28,35) //months are represented by


0 to 11
today.toLocaleDateString()
Date::toLocaleTimeString ( );
Converts a date to a string, returning the date portion using the current locale's conventions.
See also:
Date::toString ( );

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 = new Date(95,11,18,17,28,35) //months are represented by


0 to 11
today.toLocaleTimeString()

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;

Today = new Date();


hrs = Today.getUTCHours();
Date::getUTCMilliseconds ( );
Returns the milliseconds in the specif ied date according to universal time. The value returned
by getUTCMilliseconds is an integer between 0 and 999.

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

Date::setUTCFullYear ( yearValue[, monthValue[, dayValue]] );


Sets the f ull year for a specified date according to universal time.
Parameters
yearValue - An integer specifying the numeric value of the year, for example, 1995.
monthValue - An integer between 0 and 11 representing the months January through December.
dayValue - An integer f rom 1 to 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. If a parameter you specif y is out side of t he ex pect ed
range, setUTCFullYear attempts to update the other parameters and the date inf ormation in
the Date object accordingly. For example, if you specify 15 for monthValue, the year is incremented by 1
(year + 1), and 3 is used for the month.
theBigDay = new Date();
theBigDay.setUTCFullYear(1997);
Date::setUTCHours ( hoursValue[, minutesValue[, secondsValue[, msValue]]] );
Sets the hour for a specified date according to universal time.
Parameters
hoursValue - An integer between 0 and 23, representing the hour.
minutesValue - An integer between 0 and 59, representing the minutes.
secondsValue - An integer between 0 and 59, representing the seconds. If you specif y
the secondsValue parameter, you must also specify the minutesValue.
msValue - A number between 0 and 999, representing the milliseconds. If you specif y
the msValue parameter, you must also specify the minutesValue and secondsValue.
If you do not specify the minutesValue, secondsValue, and msValue parameters, the values ret urned
f rom the getMinutes, getSeconds, and getMilliseconds methods are us ed. If a parameter y ou
specify is outside of the expected range, setUTCHours attempts to update the other parameters and t he
date inf ormation in the Date object accordingly. For example, if y ou us e 100 f or secondsValue, t he
minutes will be incremented by 1 (min + 1), and 40 will be used for seconds.
theBigDay = new Date();
theBigDay.setUTCHours(8);
Date::setUTCMilliseconds ( millisecondsValue );
Sets the milliseconds for a specified date according to universal time.
Parameter
millisecondsValue - A number between 0 and 999, representing the milliseconds.
If a parameter you specify is outside of the expected range, setUTCMilliseconds attempts to update t he
other parameters and the date information in the Date object accordingly. For ex ample, if y ou use 1100
f or millisecondsValue, the seconds stored in the Date object will be incremented by 1, and 100 will be
used f or milliseconds.
theBigDay = new Date();
theBigDay.setUTCMilliseconds(500);

77
PROJECT EDITOR
6

Date::setUTCMinutes ( minutesValue[, secondsValue[, msValue]] );


Sets the minutes for a specified date according to universal time.
Parameters
minutesValue - An integer between 0 and 59, representing the minutes.
secondsValue - An integer between 0 and 59, representing the seconds. If you specif y
the secondsValue parameter, you must also specify the minutesValue.
msValue - A number between 0 and 999, representing the milliseconds. If you specif y
the msValue parameter, you must also specify the minutesValue and secondsValue.
If you do not specif y the secondsValue and msValue parameters, the values returned f rom
the getSeconds and getMilliseconds methods are used. If a parameter you specify is out side of t he
expected range, setUTCMinutes attempts to update the other parameters and t he d ate inf ormat ion in
theDate object accordingly. For example, if you use 100 for secondsValue, the minutes (minutesValue)
will be incremented by 1 (minutesValue + 1), and 40 will be used for seconds.
theBigDay = new Date();
theBigDay.setUTCMinutes(43);
Date::setUTCMonth ( monthValue[, dayValue] );
Sets the month for a specified date according to universal time.
Parameters
monthValue - An integer between 0 and 11 representing the months January through December.
dayValue - An integer from 1 to 31, representing the day of the month.
If you do not specify the dayValue parameter, the value returned from the getUTCDate method is used. If
a parameter you specify is outside of the expected range, setUTCMonth att empt s t o updat e the d ate
inf ormation in the Date object accordingly. For example, if you use 15 for monthValue, t he y ear will be
incremented by 1 (year + 1), and 3 will be used for month.
theBigDay = new Date();
theBigDay.setUTCMonth(11);
Date::setUTCSeconds ( secondsValue[, msValue] );
Sets the seconds for a specified date according to universal time.
Parameters
secondsValue - An integer between 0 and 59, representing the seconds.
msValue - A number between 0 and 999, representing the milliseconds.
If you do not specify the msValue parameter, the value returned from the getUTCMilliseconds method
is used. If a parameter you specify is outside of the expected range, setUTCSeconds attempt s t o updat e
the date inf ormation in the Date object accordingly. For example, if you use 100 f orsecondsValue, t he
minutes stored in the Date object will be incremented by 1, and 40 will be used for seconds.
theBigDay = new Date();
theBigDay.setUTCSeconds(20);
Date::toUTCString ( );
Converts a date to a string, using the universal time convention.
The value returned by toUTCString is a readable string formatted ac cording t o UTC c onv ent ion. The
f ormat of the return value may vary according to the platform.
var today = new Date();
var UTCstring = today.toUTCString();
// Mon, 03 Jul 2006 21:44:38 GMT

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()

Number constructor documentation


Numbers are not normally constructed, but instead created by simple assignment, such as, for example:

var x = 3.142;

Number function documentation


Number::toString ( [radix] );
Returns the number as a string value.
Parameter:
radix - An integer between 2 and 36 specifying the base to use for representing numeric values.

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 count = 10;


print(count.toString()); // displays "10"
print((17).toString()); // displays "17"

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

toFixed throws the following


• RangeError - If digits is too small or too large. Values between 0 and 20, inclusive, will not c ause
a RangeError. Implementations are allowed to support larger and smaller values as well.
• TypeError - If this method is invoked on an object that is not a Number.

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.

var num = 5.123456;


print("num.toPrecision() is " + num.toPrecision()); //displays
5.123456
print("num.toPrecision(4) is " + num.toPrecision(4)); //displays
5.123
print("num.toPrecision(2) is " + num.toPrecision(2)); //displays
5.1
print("num.toPrecision(1) is " + num.toPrecision(1)); //displays
5
Number::valueOf ( );
Returns the primitive value of a Number object as a number data type.
var x = new Number();
print(x.valueOf()); // prints "0"

Number properties documentation


MAX_VALUE
Returns the maximum value for floating point values.
MIN_VALUE
Returns the minimum value for floating point values.
NaN
A value representing Not-A-Number. NaN is always unequal to any other number, including NaN itself; y ou
cannot check for the not-a-number value by comparing to Number.NaN. Use the isNaN() f unction instead.
NEGATIVE_INFINITY

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.

Array RegExp::exec(String str);


Boolean RegExp.test([String str])
String RegExp::toString( );
String RegExp::valueOf( )

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");

Special characters in regular expressions


Character Meaning
For characters that are usually treated literally, indicates that the next charact er is s pecial
and not to be interpreted literally.
For example, /b/ matches the character 'b'. By placing a backslash in f ront of b, t hat is by
using /\b/, the character becomes special to mean match a word boundary.
or
\
For characters that are usually treated specially, indicates that the next character is not
special and should be interpreted literally.
For example, * is a special character that means 0 or more occurrences of the p receding
character should be matched; f or example, /a*/ means match 0 or more "a"s. To
match * literally, precede it with a backslash; for example, /a\*/ matches 'a*'.

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

[\b] Matches a backspace. (Not to be confused with \b.)


Matches a word boundary, such as a space. (Not to be confused with [\b].)
\b For example, /\bn\w/ matches the 'no' in "noonday"; /\wy\b/ matches the 'ly' in
"possibly yesterday."
Matches a non-word boundary.
\B For example, /\w\Bn/ matches 'on' in "noonday", and /y\B\w/ matches 'ye' in " pos sibly
yesterday."
Where X is a letter f rom A - Z. Matches a control character in a string.
\cX
For example, /\cM/ matches control-M in a string.
Matches a digit character in the basic Latin alphabet. Equivalent to [0-9].
\d
For example, /\d/ or /[0-9]/ matches '2' in "B2 is the suite number."
Matches any non-digit character in the basic Latin alphabet. Equivalent to [^0-9].
\D
For example, /\D/ or /[^0-9]/ matches 'B' in "B2 is the suite number."
\f Matches a f orm-feed.
\n Matches a linefeed.
\r Matches a carriage return.
Matches a single white space character, including space, tab, form feed, line feed and other
\s unicode spaces. 1
For example, /\s\w*/ matches ' bar' in "foo bar."

\S Matches a single character other than white space. 2


For example, /\S\w*/ matches 'foo' in "foo bar."
\t Matches a tab.
\v Matches a vertical tab.
Matches any alphanumeric character f rom the basic Latin alphabet, including the
\w underscore. Equivalent to [A-Za-z0-9_].
For example, /\w/ matches 'a' in "apple," '5' in "$5.28," and '3' in "3D."
Matches any character that is not a word character from the basic Latin alphabet. Equivalent
\W to [^A-Za-z0-9_].
For example, /\W/ or /[^$A-Za-z0-9_]/ matches '%' in "50%."
Where n is a positive integer. A back ref erence to the last substring matching the n
\n parenthetical in the regular expression (counting left parentheses).
For example, /apple(,)\sorange\1/ matches 'apple, orange,' in "apple, orange, cherry ,
peach."
\0 Matches a NUL character. Do not follow this with another digit.
\xhh Matches the character with the code hh (two hexadecimal digits.)
\uhhhh Matches the character with the Unicode value hhhh (four hexadecimal digits).
1
equivalent_s - Equivalent to: [\t\n\v\f \r
\u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u20
29\u3000]
2
equivalent_S - Equivalent to: [^\t\n\v\f \r
\u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u20
29\u3000]

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.

RegExp functions documentation


RegExp::exec(String str);
Executes a search for a match in a specified string. Returns a result array, or null.
Parameter:
str - The string against which to match the regular expression.
As shown in the syntax description, a regular expression's exec method c an be c alled eit her d irec tly,
(with regexp.exec(str)) or indirectly (with regexp(str)). If you are executing a match s imply t o f ind
true or f alse, use the test method or the String search method.
If the match succeeds, the exec method returns an array and updates properties of the regular expres sion
object. If the match fails, the exec method returns null.

Consider the following example:

// Match one d followed by one or more b's followed by one d


// Remember matched b's and the following d
// Ignore case
var myRe = /d(b+)(d)/ig;
var myArray = myRe.exec("cdbBdbsbz");

The f ollowing table shows the results for this script:

Object Property/Index Description Example


["dbBd",
The content of myArray.
"bB", "d"]
index The 0-based index of the match in the string. 1
input The original string. cdbBdbsbz
MyArray
[0] The last matched characters. dbBd
The parenthesized substring matches, if any. The [1] = bB
[1], ...[n] number of possible parenthesized substrings is [2] = d
unlimited.

86
LASER ENGINE LANGUAGE REFERENCE
6

lastIndex The index at which to start the next match. 5


IgnoreCase Indicates if the "i" flag was used to ignore case. true
global Indicates if the "g" flag was used for a global match. true
MyRe
Indicates if the "m" flag was used to search in strings across
multiline false
multiple line.
source The text of the pattern. d(b+)(d)

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

Example: Using exec to execute a match against the input


In the f ollowing example, the function executes a match against the input. It then cycles through the array t o
see if other names match the user's name.
This script assumes that first names of registered party attendees are preloaded into the array A, perhaps by
gathering them from a party database.
var A = ["Frank", "Emily", "Jane", "Harry", "Nick", "Beth",
"Rick", "Terrence", "Carol", "Ann", "Terry", "Frank",
"Alice", "Rick", "Bill", "Tom", "Fiona", "Jane", "William",
"Joan", "Beth"];

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.

RegExp properties documentation


Note that several of the RegExp properties have both long and short (Perl-like) names. Both names
always ref er to the same value. Perl is the programming language f rom which Laser Engine Program
modeled its regular expressions.
constructor
Specifies the function that creates an object's prototype.
Returns a ref erence to the RegExp function that created the instance's prototype. Note that the value of this
property is a ref erence to the function itself, not a string containing the function's name.
global
Whether to test the regular expression against all possible matches in a string, or only against the
f irst. global is a property of an individual regular expression object.
The value of global is true if the "g" flag was used; otherwise, false. The "g" flag indicates t hat t he reg ular
expression should be tested against all possible matches in a string.
You cannot change this property directly.
ignoreCase
Whether to ignore case while attempting a match in a string. ignoreCase is a p ropert y of an individual
regular expression object.
The value of ignoreCase is true if the "i" flag was used; otherwise, false. The "i" flag indicates t hat c ase
should be ignored while attempting a match in a string.
You cannot change this property directly.
lastIndex
A read/write integer property that specifies the index at which to start t he nex t mat ch. lastIndex is a
property of an individual regular expression object.
This property is set only if the regular expression used the "g" flag to indicate a global search.
The f ollowing rules apply:

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.

For example, consider the following sequence of statements:


re = /(hi)?/g - Matches the empty string.
re("hi") - Returns ["hi", "hi"] with lastIndex equal to 2.
re("hi") - Returns [""], an empty array whose zeroth element is the match string. In this
case, the empty string because lastIndex was 2 (and still is 2) and "hi" has length 2.

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...

Static String functions


String String::fromCharCode ( Number code1, Number code2,... );

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"

Static String function documentation


String::fromCharCode ( Number code1, Number code2,... );
Returns a string made up of the characters with code code1, code2, et c. , ac cording t o t heir Unic ode
character codes.
var s = String.fromCharCode( 65, 66, 67, 68 );
println( s ); // prints "ABCD"

String functions documentation


String::charAt ( Number pos );
Returns the character in the string at position pos. If the position is out of bounds, undefined is returned.
Parameter:
Pos - An integer between 0 and 1 less than the length of the string.

90
LASER ENGINE LANGUAGE REFERENCE
6

The f ollowing example displays characters at different locations in the string "Brave new world":

var anyString="Brave new world"

print("The character at index 0 is '" + anyString.charAt(0) +


"'")
print("The character at index 1 is '" + anyString.charAt(1) +
"'")

These lines display the following:

The character at index 0 is 'B'


The character at index 1 is 'r'
String::charCodeAt ( Number pos );
Returns the character code of the character at position pos in the string. If the position is out of
bounds, undefined is returned.
Parameter:
Pos - An integer greater than 0 and less than the length of the string; if unspecified, defaults to 0.

The f ollowing example returns 65, the Unicode value for A:

"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":

var anyString="Brave new world"


print("<The index of the first w from the beginning is " +
anyString.indexOf("w")) // Displays 8

91
PROJECT EDITOR
6

String::lastIndexOf ( String or RegExp pattern, Number pos );


Returns the last index of pattern in the string, starting at position pos and searc hing b ackwards f ro m
there. If no position is specified, the function starts at the end of the string. If the pattern is not f ound in t he
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, indexed from left to right. It can b e
any integer between 0 and the length of the string. The default value is the length of the string.

The f ollowing example uses lastIndexOf to locate a value in the string "Brave new world":

var anyString="Brave new world"


print("<The index of the first w from the end is " +
anyString.lastIndexOf("w")) // Displays 6
String::match ( RegExp pattern );
Returns the matched pattern if this string matches the pattern defined by regexp. If t he s tring does n't
match or regexp is not a valid regular expression, undefined is returned.
String::replace ( RegExp pattern, String newValue );
Replaces the first occurrence of pattern in the string with newvalue if the pattern is found in the string. A
modified copy of string is returned.
If pattern is a regular expression with global set, all occurrences of pattern in the string will be replaced.
String::search ( RegExp pattern );
Executes the search for a match between a regular expression and this String object.
If successful, search returns the index of pattern inside the string.

The f ollowing example prints a message which depends on the success of the test:

function testinput(re, str){


if (string.search(re) != -1)
midstring = " contains ";
else
midstring = " does not contain ";
print (str + midstring + re.source);
}
String::slice ( beginslice[, endSlice]);
Extracts a section of a string and returns a new string. Changes to the text in one string do not af fect t he
other string.
Parameters:
beginSlice - The zero-based index at which to begin extraction.
endSlice - The zero-based index at which to end extraction. If omitted, slice extracts to the end of t he
string.

92
LASER ENGINE LANGUAGE REFERENCE
6

The f ollowing example uses slice to create a new string:


var str1 = "The morning is upon us.";
var str2 = str1.slice(3, -2);
print(str2);
This writes:
morning is upon u
String::split ([separator][, limit]);
Splits a String object into an array of strings by separating the string into substrings.
Parameters:
separator - Specifies the character to use for separating the string. The separator is treated as a string
or a regular expression (see RegExp). If separator is omitted, the array returned contains one element
consisting of the entire string.
limit - Integer specifying a limit on the number of splits to be found.

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";

var space = " ";


var comma = ",";

splitString(tempestString, space);
splitString(tempestString);
splitString(monthString, comma);

93
PROJECT EDITOR
6

This example produces the following output:


The original string is: "Oh brave new world that has such people
in it."
The separator is: " "
The array has 10 elements: Oh / brave / new / world / that / has
/ such / people / in / it. /

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 original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,


Oct,Nov,Dec"
The separator is: ","
The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun /
Jul / Aug / Sep / Oct / Nov / Dec /
String::substring ( Number startIndex, Number endIndex );
Returns a copy of this string which is the substring starting at startIndex and ending at endIndex.
Parameters:
startIndex - An integer between 0 and one less than the length of the string.
endIndex - An integer between 0 and the length of the string.

The f ollowing example uses substring to display characters from the string "Laser Editor".

// assumes a print function is defined


var anyString = "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.

The f ollowing example displays the string value of a String object:

x = new String("Hello world");


alert(x.toString()) // Displays "Hello world"
String::toUpperCase ( );
Returns the value of the string converted to uppercase. toUpperCase does not affect the value of the string
itself .

String property documentation


length
A value that specifies the length of the string.

94
LASER ENGINE LANGUAGE REFERENCE
6

6.6.2 Arguments variable


The arguments object is a local variable available within all functions.

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

6.6.3 Built-in Constants

Laser Engine Program provides a number of convenient built-in constants.

For f urther information:


• Inf inity
• NaN
• undef ined

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

6.6.4 Built-in Functions


Laser Engine Program provides the following built-in functions.

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:

Example without arguments:


function myInterestingScriptFunction() { ... }
...
myQObject.somethingChanged.connect(myInterestingScriptFunction);

Example with arguments:


function myInterstingScriptFunction2(arg1,arg2) { ... }
...
myQObject["somethingChanged2(arg1,arg2)"]
.connect(myInterestingScriptFunction2);

Note that the f unction is resolved when the connection is made, not when the signal is emitted.

• Back to the full list of Built-in Functions

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);

• Back to the full list of Built-in Functions

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.

• Back to the full list of Built-in Functions

isFinite()
Syntax:
isFinite( expression )

Returns true if the expression's value is a number that is within range; otherwise returns false.

• Back to the full list of Built-in Functions

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"

• Back to the full list of Built-in Functions

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:

• base 16 (hexadecimal) if the first non-whitespace characters are "0x" or "0X"


• base 8 (octal) if the first non-whitespace character is "0"
• base 10 otherwise

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

• See also parseFloat().

99
PROJECT EDITOR
6

6.6.5 Built-in Operators


Laser Engine Program provides a set of built-in operators, which are divided into the following types:
• Assignment Operators
• Arithmetic Operators
• String Operators
• Logical Operators
• Comparison Operators
• Bit-wise operators
• Special Operators

Assignment Operators
These operators are used to assign the value of expressions to variables:

= operator &= operator


+= operator ^= operator
-= operator |= operator
*= operator <<= operator
/= operator >>= operator
%= operator >>>= operator

= operator
var variable = expression;
The assignment operator is used to assign the value of an expression to the variable.

It is an error to attempt to assign to a constant.

+= operator
variable += expression;

This operator adds the value of the expression to the variable. It is the same as:

variable = variable + expression;

but is shorter to write, and less error-prone.

See also String Operators (+= string)

-= 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

These operators are used to perform arithmetic computations on their operands.

+ operator * operator
++ operator / operator
- operator % operator
-- operator

+ operator
operand1 + operand2

This operator returns the result of adding the two operands (operand1 and operand2).

See also String Operators (+ string)

++ operator
++operand; // pre-increment
operand++; // post-increment

The pre-increment version of this operator increments the operand, and returns the value of the (now
incremented) operand.
The post-incremented version of this operator returns the value of the operand, and then increments
the operand.

- 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).

The String operators are described in the table below:


Operator Syntax Description
This operator returns a string that is the concatenation of its operands,
+ string str1 + str2 (str1 and str2).
See also Arithmetic Operators (+ operator).
This operator appends its second operand (str2) onto the end of t he
+= string str1 += str2 f irst operand (str1).
See also Assignment Operators (+= operator).

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.

The Logical operators are described in the table below:

Operator Syntax Description


This operator returns an object whose value is true if bot h its operands
are true; otherwise it returns an object whose value is false.
operand1 &&
&& Specif ically, if the value of operand1 is false, the operator
operand2
returns operand1 as its result. If operand1 is true, the operator
returns operand2.
This operator returns an object whose value is true if either of its
operands are true; otherwise it returns an object whose value is false.
operand1 ||
|| Specif ically, if the value of operand1 is true, the operator
operand2
returns operand1 as its result. If operand1 is false, the operator
returns operand2.
If the operand's value is true, this operator returns false; ot herwise it
! ! operand
returns true.

103
PROJECT EDITOR
6

Comparison Operators

Comparison operators are used to compare objects and their values.

The f ollowing table summarizes comparison operators:

Operator Syntax Description


operand1 ==
== Returns true if the operands are equal; otherwise returns false.
operand2
operand1 !=
!= Returns true if the operands are not equal; otherwise returns false.
operand2
operand1 === Returns true if the operands are equal and of the same type; otherwise
= = =
operand2 returns false.
operand1 !== Returns true if the operands are not equal or if the operands are of
!==
operand2 dif ferent types; otherwise returns false.
operand1 > Returns true if operand1 is greater than operand2; otherwise
>
operand2 returns false.
>= operand1 >= Returns true if operand1 is greater than or equal to operand2;
operand2 otherwise returns false.

< 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.

The f ollowing table summarizes bit-wise operators:

Operator Syntax Description


operand1 & Returns the result of a bit-wise AND on the operands
&
operand2 (operand1 and operand2).
operand1 ^ Returns the result of a bit-wise XOR on the operands
^
operand2 (operand1 and operand2).
operand1 | Returns the result of a bit-wise OR on the operands
|
operand2 (operand1 and operand2).
~ ~ operand Returns the bit-wise NOT of the operand.
operand1 << Returns the result of a bit-wise left shift of operand1 by the number of bit s
<<
operand2 specified by operand2. Zeros are shifted in from the right.
operand1 >> Returns the result of a bit-wise (sign propagating) right shift of operand1 by
>>
operand2 the number of bits specified by operand2.
operand1 >>> Returns the result of a bit-wise (zero filling) right shif t of operand1 b y t he
>>>
operand2 number of bits specified by operand2. Zeros are shifted in from the left.

104
LASER ENGINE LANGUAGE REFERENCE
6

Special Operators
The f ollowing special operators are available:

?: operator instanceof operator


, operator new operator
f unction operator this operator
in operator typeof operator

?: 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).

To illustrate the concept of binding, refer to the following example.

Example:
function Car(brand) {
this.brand = brand;
}

Car.prototype.getBrand = function() {
return this.brand;
}

var foo = new Car("toyota");


print(foo.getBrand());

As expected, this outputs "toyota".

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

You might also like