TR0120 (v1.1) April 26, 2005 1 Delphi Script Reference Summary Technical Reference TR0120 (v1.1) April 26, 2005 This reference manual describes the Delphi Script language. This reference includes the following topics: • Exploring the Delphi Script language • Delphi Script source files • Creating new scripts • Adding scripts to a project • Executing a script in Altium Designer • Assigning a script to a process launcher • About Delphi Script examples • Writing Delphi Script scripts • Delphi Script keywords • Delphi Script statements • Delphi Script functions • Forms and Components. Exploring the Delphi Script Language Introduction This Delphi Script reference details each of the statements, functions and extensions that are supported. These are special procedures that are used to control and communicate directly with the Design Explorer. It is assumed that you are familiar with basic programming concepts as well as the basic operation of your Design Explorer-based software. The scripting system supports the Delphi Script language which is very similar to Borland Delphi (TM). The key difference is that, Delphi Script is a typeless or untyped scripting language which means you cannot define records or classes and pass pointers as parameters to functions for example. You can still declare variables within scripts for readability. The Delphi Script Reference Help contains reference material on interfaces, components, global routines, types, and variables that make up the DelphiScript scripting language.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
TR0120 (v1.1) April 26, 2005 1
Delphi Script Reference
Summary Technical Reference TR0120 (v1.1) April 26, 2005
This reference manual describes the Delphi Script language.
This reference includes the following topics:
• Exploring the Delphi Script language
• Delphi Script source files
• Creating new scripts
• Adding scripts to a project
• Executing a script in Altium Designer
• Assigning a script to a process launcher
• About Delphi Script examples
• Writing Delphi Script scripts
• Delphi Script keywords
• Delphi Script statements
• Delphi Script functions
• Forms and Components.
Exploring the Delphi Script Language
Introduction This Delphi Script reference details each of the statements, functions and extensions that are supported. These are special procedures that are used to control and communicate directly with the Design Explorer. It is assumed that you are familiar with basic programming concepts as well as the basic operation of your Design Explorer-based software.
The scripting system supports the Delphi Script language which is very similar to Borland Delphi (TM). The key difference is that, Delphi Script is a typeless or untyped scripting language which means you cannot define records or classes and pass pointers as parameters to functions for example. You can still declare variables within scripts for readability.
The Delphi Script Reference Help contains reference material on interfaces, components, global routines, types, and variables that make up the DelphiScript scripting language.
Delphi Script Reference
2 TR0120 (v1.1) April 26, 2005
Objects An object consists of methods, and in many cases, properties, and events. Properties represent the data contained in the object. Methods are the actions the object can perform. Events are conditions the object can react to. All objects descend from the ancestor object TObject.
Interfaces An interface consists of methods, and in many cases, properties but cannot have data fields. An interface represents an existing object and each interface has a GUID which marks it unique. Properties represent the data contained in the object that the interface is associated with. Methods are the actions the object (in which the interface is associated with) can perform.
Components Components are visual objects that you can manipulate at design time from the Tool Palette panel. All components descend from the TComponent class in the Borland Delphi Visual Component Library.
Routines Global routines are the procedures and functions from the scripting system. These routines are not part of a class, but can be called either directly or from within class methods on your scripts.
Types The types described in the Help are used as return types and parameter types for interface methods and properties and object's methods, properties and events, and for global routines. In many cases, types are documented in the Enumerated Types sections in each DXP Object Model reference help.
DXP and Borland Delphi Run Time Libraries The Scripting system also supports a subset of Borland Delphi Run Time Library (RTL) and a subset of DXP RTL which is covered in the DXP RTL Reference.
Server Processes A script can execute server processes and thus server processes and parameters are covered in the Server Process Reference.
Delphi Script source files You open a script project in Altium Designer and you can edit the contents of a script inside the Altium Designer. A script project is organized to store script documents (script units and script forms). You can execute the script from a menu item, toolbar button or from the Run Script dialog from the Altium Designer’s system menu.
PRJSCR, PAS and DFM files The scripts are organized into projects with a PRJSCR extension. Each project consists of files with a pas extension. Files can be either script units or script forms (each form has a script file with pas extension and a corresponding form with a dfm extension). A script form is a graphical window that hosts different controls that run on top of Altium Designer.
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 3
However it is possible to attach scripts to different projects and it is highly recommended to organize scripts into different projects to manage the number of scripts and their procedures / functions.
Scripts (script units and script forms) consist of functions/procedures that you can call within Altium Designer.
Creating new scripts You can add existing or new scripts into the specified project in the Projects panel in Altium Designer. There are two types of scripts : Script Units and Script Forms. With a project open in Altium Designer, right click on a project in the Projects panel, and a pop up menu appears, click on the Add New to Project item, and choose Script Unit. A new script appears.
A script can have at least one procedure which defines the main program code. You can, however, define other procedures and functions that can be called by your code. Functions and procedures are defined within a Begin End statement block as well as functions.
It is possible to have no procedures or functions within a script but at least it is necessary to have a Begin End. (with the full stop at end of the End keyword) block so that the script can have a chance to get executed.
Example of a procedure Procedure CreateSchObjects;
Begin
If SchServer = Nil Then Exit;
SchDoc := SchServer.GetCurrentSchDocument;
If SchDoc = Nil Then Exit;
PlaceSchematicObjects;
SchDoc.GraphicallyInvalidate;
End;
Example of Begin End. block Begin
ShowMessage('The dialog will appear when you run this script');
End.
If you have a statement in your script but there is no Begin End. block or no procedures, then the script will not be executed.
Adding scripts to a project You can add existing scripts to a specified project in the Projects panel in Altium Designer. With a project open in Altium Designer, right click on this project in the Projects panel, and a pop up menu appears, click on the Add Existing to Project... item.
A Choose Documents To Add to Project dialog appears. You can multi-select as many scripts you want to add into the specified project.
Delphi Script Reference
4 TR0120 (v1.1) April 26, 2005
Executing a script in Altium Designer
In Text Editor workspace You can configure the Run command when you are in the text editor to point to a script and execute it. Every time you click on the Run icon from the Text Editor menu or press F5, the scripting system executes the script pointed to by the Set Project Startup Procedure item. You can change the start up procedure by clicking on the Set Project Start Up Procedure item in the Run menu which invokes the Select Item to Run dialog. You can then select which procedure of a script to be set.
Executing a script on a design document To execute a script in Altium Designer, there are two methods and there are two different dialogs for each method. These methods are necessary if you wish to run a script on a server specific document such as PCB or Schematic documents.
1. Using the Select Item To Run dialog to execute a script Click on the Run Script from the system menu and the Select Item to Run dialog appears with a list of procedures (those parameter-less procedures/functions only appear) within each script in a opened project.
Note that you can also click on a script unit filename within this Select Item to Run dialog and the functionless/procedureless Begin End. block within the script gets executed. See code example here
Script unit Var
Begin
//script here with no function/procedure
A := 50;
A := A + 1;
ShowMessage(IntToStr(A));
End.
Now, only parameter-less functions and procedures for each script of an opened project only appear on the Select Item to Run dialog. It is a good idea for script writers to write the functions in scripts so that they will appear in this dialog and the other functions with parameters not to appear in this same dialog.
When you are working in a different editor such as PCB editor, you can assign the script to a process launcher and use it to run a specified script easily. See the Assigning a script to a process launcher.
You can add a list of installed script projects so that, every time you invoke the Select item to Run dialog, the installed script projects will appear along with other script projects currently open in the Projects panel. Invoke Scripting System Settings item from Tools » Scripting Preferences menu in the TextEditor workspace and the Scripting System Settings dialog appears.
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 5
2. Using the Run Process dialog to execute a script Invoke the Run Process dialog from the System menu and execute the ScriptingSystem:RunScript process in the Process: field and specify the script parameters, the ProjectName parameter which is the path to the project name and the ProcName parameter to execute the specified procedure from a specified script in the Parameters: field. You need the following parameters for the ScriptingSystem:RunScript process to execute a specified script.
Process: ScriptingSystem:RunScript
Parameters: ProjectName (string - full path to a script project) ProcName (string - script name > procedure name)
To run a script repeatedly in the text editor, assign the script to the Set Project Startup Procedure item from the Run menu of the Text editor server. you can then click on the Run button. or press F5 to execute this script. To run a different script, you will need to re-invoke the Set Project Startup Procedure from the Run menu and assign a new script to it.
You can click on the Run Script item from the system menu and the Select Item to Run dialog appears with a list of procedures (those parameterless procedures/functions only appear) within each script in a project. This may be needed if you wish to run a script on a specific document type such as PCB or Schematic documents.
You can also use the Run Process dialog and specify the scriptingsystem server process and specify the parameters for this scripting system server to execute a script, this may also be needed if you wish to run a script on a specific document type such as PCB or Schematic documents.
Assigning a script to a menu, toolbar or key You have the ability to assign a script to a server menu, toolbar or hot key in Altium Designer which makes it possible for you to run the script over a current PCB document for example. You will need to specify the full path to a project where the script resides in and specify which unit and procedure to execute the script. There are two parameters in this case: the ProjectName and the ProcName. For the ProcName parameter, you need to specify the script filename and the procedure. So the format is as follows: ProcName = ScriptFileName>ProcedureName. Note the GreaterThan (>) symbol used between the script file name and the procedure name.
Delphi Script Reference
6 TR0120 (v1.1) April 26, 2005
Assigning to a process launcher example To illustrate this ability to assign a script to a resource, we will open a PCB document in Altium Designer and use the HelloWorld script example from the \Scripts\General\ folder.
1. Double click on the PCB menu and the Customizing PCB Editor dialog appears. 2. Click on the New button from the Customizing PCB Editor dialog.
3. Choose ScriptingSystem:RunScript process in the Process: field of the Customizing PCB Editor dialog.
4. Enter ProjectName = C:\Program Files\Altium2004\Examples\Scripts\General\HelloWorld.PrjScr | ProcName = HelloWorldDialog>RunHelloWorld text in the Parameters: field for example.
5. You will need to give a name to this new command and assign a new icon if you wish. In this case,
the name is PCBScript in the Caption: field of this dialog. The new commands appear in the [Custom] category of the Categories list. Click on the [Custom] entry from the Categories list. The PCBScript command appears in the Commands list of this dialog.
6. You then need to drag the new PCBScript command onto the PCB menu from the Customizing PCB Editor dialog. The command appears on the menu. You can then click on this new command and the HelloWorldDialog form appears.
About Example Scripts The examples that follow illustrate the basic features of DelphiScript programming. The examples show simple scripts for the Altium Designer application. The example scripts are organized into Scripts folder and its sub folders; General, Processes, PCB, Schematic and WSM folders accordingly.
\DelphiScript Scripts\General sub folder - Demonstrate Delphi Script keywords • Hello World script - introductory script
• IniFileEg - demo the use of the TINIFile object
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 7
• Mandelbrot script - showing off the graphical capabilities of Delphi Script
• ShowModalEg script - demo the use of ModalResult of a script form.
• Sinewave script - demo the graphical capabilities
• TicTac script - demo various Delphi Script keywords and to have fun!
• UpdateTime - demo the use of a Timer component.
\DelphiScript Scripts\Processes sub folder - Demonstrate server processes Various scripts which use different server processes and parameters.
\DelphiScript Scripts\DXP sub folder - Demonstrate Client and system API Various scripts that demonstrate several aspects of the Client API
\DelphiScript Scripts\Sch subfolder - Demonstrate SCH API Various scripts that demonstrate several aspects of the Schematic API
\DelphiScript Scripts\PCB subfolder - Demonstrate PCB API Various scripts that demonstrate several aspects of the PCB API
\DelphiScript Scripts\WSM subfolder - Demonstrate WSM API Various scripts that demonstrate several aspects of the Work Space Manager API.
Delphi Script Reference
TR0120 (v1.0) December 01, 2004 8
Writing DelphiScript Scripts In this Writing DelphiScript Scripts section:
• DelphiScript naming conventions
• Local and Global Variables
• Using named variables in a script
• Functions and procedures in a script
• Including comments in scripts
• Splitting a line of script
• Case sensitivity
• The space character
• Calculating expressions with the evaluate function
• Exiting from a procedure
• Passing parameters to functions and procedures
• Using DXP objects in scripts
• Tips on writing scripts
• Differences between DelphiScript and Object Pascal
• DelphiScript Error Codes.
Delphi Script naming conventions In general, there is no restriction to the names you can give to procedures, functions, variables and constants as long as they adhere to the following rules:
• The name can contain the letters A to Z, a to z, the underscore character "_" and the digits 0 to 9.
• The name must begin with a letter.
• The name cannot be a Delphi Script keyword, directives or reserved word.
• Names are case insensitive when interpreted. You may use both upper and lower case when naming a function, subroutine, variable or constant, however the interpreter will not distinguish between upper and lower case characters. Names which are identical in all but case will be treated as the same name in Delphi Script.
In a Delphi script file, the functions and procedures are declared using the Procedure Begin End or Function Begin End block or Var Begin End block. Both of these statement blocks require a name to be given to the procedure or function. Delphi Script allows you to create named variables and constants to hold values used in the current script.
Including comments in scripts In a script, comments are non-executed lines of code which are included for the benefit of the programmer. Comments can be included virtually anywhere in a script. Any text following //, or enclosed with (* *) or {} are ignored by Delphi Script.
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 9
// Comment type example //This whole line is a comment
{} Comment type example {This whole line is a comment}
(* *) comment type example (*
This whole line is a comment
This whole line is a comment
This whole line is a comment
*)
Comments can also be included on the same line as executed code. For example, everything after the semi colon in the following code line is treated as a comment. ShowMessage (‘Hello World’); //Display Message
Local and Global Variables
Local and Global variables Since all scripts have local and global variables, its very important to have unique variable names in your scripts within a script project. If the variables are defined outside any procedures and functions, they are global and can be accessed by any unit in the same project.
If variables are defined inside a procedure or function, then these local variables are not accessible outside these procedures/functions.
Example of local and global variables in a script // The Uses keyword is not needed.
// Variables from UnitA script are available to this unit script,
// as long UnitA is in the same project as this Unit script.
Const
GlobalVariableFromThisUnit='Global Variable from this unit';
Procedure TestLocal;
var
Local;
Begin
// can we access a variable from UnitA without the Uses
Local := 'Local Variable';
ShowMessage(Local);
End;
Delphi Script Reference
10 TR0120 (v1.1) April 26, 2005
Procedure TestGlobal;
Begin
//ShowMessage(Local); // produces an error.
ShowMessage(GlobalVariableFromThisUnit);
ShowMessage(GlobalVariableFromUnitA);
End;
Unit A script Const
GlobalVariableFromUnitA = 'Global Variable from Unit A';
Using named variables in a script In a script, you use named variables or constants to store values to be used during program execution. All variables in a script are always of Variant type. Typecasting is ignored. Types in variables declaration are ignored and can be skipped, so these declarations are correct: var a : integer;
var b : integer;
var c, d;
Splitting a line of script Each code statement is terminated with the semi-colon " ; " character to indicate the end of this statement. Delphi Script allows you to write a statement on several lines of code, splitting a long instruction on two or more lines. The only restriction in splitting programming statements on different lines is that a string literal may not span several lines.
For example: X.AddPoint( 25, 100);
X.AddPoint( 0, 75);
// is equivalent to:
X.AddPoint( 25, 100); X.AddPoint( 0, 75);
But ‘Hello World!’
is not equivalent to ‘Hello
World!’
Delphi Script does not put any practical limit on the length of a single line of code in a script, however, for the sake of readability and ease of debugging it is good practice to limit the length of code lines so that they can easily be read on screen or in printed form.
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 11
If a line of code is very long, you can break this line into multiple lines and this code will be treated by the Delphi Script interpreter as if it were written on a single line.
Unformatted code example If Not (PcbApi_ChooseRectangleByCorners(BoardHandle,'Choose first corner','Choose final corner',x1,y1,x2,y2)) Then Exit;
Formatted code example If Not (PcbApi_ChooseRectangleByCorners(BoardHandle,
'Choose first corner',
'Choose final corner',
x1,y1,x2,y2)) Then Exit;
Case sensitivity The Delphi Script language used in writing scripts is not case sensitive, i.e. all keywords, statements, variable names, function and procedure names can be written without regard to using capital or lower case letters. Both upper and lower case characters are considered equivalent. For example, the variable name myVar is equivalent to myvar and MYVAR. Delphi Script treats all of these names as the same variable.
The only exception to this is in literal strings, such as the title string of a dialog definition, or the value of a string variable. These strings retain case differences.
The space character A space is used to separate keywords in a script statement. However, Delphi Script ignores any additional white spaces in a statement.
For example: X = 5
is equivalent to X = 5
You may use white spaces to make your script more readable.
Functions and procedures in a script The Delphi Script interpreter allows two kinds of procedures: Procedures and Functions. The only difference between a function and a procedure is that a function returns a value.
A script can have at least one procedure which defines the main program code. You can, however, define other procedures and functions that can be called by your code. As with Borland Delphi, procedures are defined within a Begin End statement block as well as functions are defined within a Begin.End statement block too.
To invoke or call a function or procedure, simply include the name of the function or procedure in a statement in the same way that you would use the built-in Delphi Script functions and procedures. If the function or procedure requires parameters, then you must include these in the calling statement. Both
Delphi Script Reference
12 TR0120 (v1.1) April 26, 2005
functions and procedures can be defined to accept parameters, but only functions can be defined to return a value to the calling statement.
You may assign any name to functions and procedures that you define, as long as it conforms to the standard Delphi Script naming conventions.
Typical Delphi Script function Function BooleanToString(AValue : Boolean) : String;
Begin
If (AValue) Then Result := 'True'
Else Result := 'False';
End;
The name of a function can not be used to set its return value. The Result keyword must be used instead.
Var Begin End global block Var
A, B, C;
Begin
B := 10;
C := 20;
A := B + C;
ShowMessage(IntToStr(A));
End.
Using DXP Objects in scripts You cannot create your own records or classes types and instantiate them in a script, however you can use DXP run time libraries and Delphi Script’s pre-defined classes for example TStringList and TList
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 13
classes and instantiate them to act as containers of data storage for your scripting needs. The list of supported Delphi RTL and Design Explorer, PCB and Schematic classes are covered in the DXP RTL reference document.
The biggest feature of Delphi Script, is that the Interfaces of DXP objects are available to use in scripts. For example you have the ability to massage design objects on Schematic and PCB documents through the use of Schematic Interfaces and PCB interfaces. Beware that the Interface keyword has two uses - the Implementation / Interface sections and the Interface / Class declaration / implementation. In this case, the interfaces are used as declarations of the classes they are associated with. Interfaces are not local to a function or to a script. Therefore DXP Interfaces are available for use on any script.
Normally in scripts, there is no need to instantiate an interface, you just extract the interface representing an existing object in Altium Designer and from this interface you can extract embedded or aggregate interface objects and from them you can get or set property values. Interface names as a convention have an I added in front of the name for example IPCB_Board represents an interface for an existing PCB document. An example of PCB interfaces in use is shown next.
Interface example Procedure ViaCreation;
Var
Board : IPCB_Board;
Via : IPCB_Via;
Begin
Board := PCBServer.GetCurrentPCBBoard;
If Board = Nil Then Exit;
(* Create a Via object *)
Via := PCBServer.PCBObjectFactory(eViaObject, eNoDimension, eCreate_Default);
Via.X := MilsToCoord(7500);
Via.Y := MilsToCoord(7500);
Via.Size := MilsToCoord(50);
Via.HoleSize := MilsToCoord(20);
Via.LowLayer := eTopLayer;
Via.HighLayer := eBottomLayer;
(* Put this via in the Board object*)
Board.AddPCBObject(Via);
End;
Delphi Script Reference
14 TR0120 (v1.1) April 26, 2005
Objects, Interfaces, functions and types in your scripts can be used from the following units:
• Supported Borland DelphiTM functions and classes and Delphi Script extensions in the Delphi Script reference document.
• Client API
• PCB Server API
• Schematic Server API
• Work Space Manager Server API
• Nexus API
• DXP RTL functions
• Parametric processes Check out the scripts in the \Altium2004\Examples\Scripts\ folder to see DXP Interfaces, Delphi objects and functions being used in scripts.
Tips on writing scripts
Referencing scripts in a script project You can have code in one script to call another procedure in another script in the same script project and access to any global variable in any script within the same project.
Local and Global variables Since all scripts have local and global variables, its very important to have unique variable names in your scripts within a script project. If the variables are defined outside any procedures and functions, they are global and can be accessed by any unit in the same project.
If variables are defined inside a procedure or function, then these local variables are not accessible outside these procedures/functions.
It is recommended to put scripts of similar nature in a project and that there are not too many scripts in a project. Keeping track of global variables in many scripts becomes an issue. It is not mandatory to store scripts in a script project, you can put scripts in other project types.
Unique identifiers and variables With script forms, ensure that all script forms have unique form names, for example it is possible (although wrong) to have all script forms be named form1 in the same script project. The scripting system gets confused when trying to display which form when a script form is executed. Change the script form name by using the Object Inspector, and the name gets changed in the script unit and in the script form DFM files automatically.
Parameter-less Procedures and Functions Try and design your scripts so that those procedures that need to be invoked to run the script will only appear in the Select Items to Run dialog. To prevent other procedures/functions from appearing in the Select Items to Run dialog, you can for example insert a (Dummy : Integer) parameter next to the method name. See the example below.
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 15
Example Function TSineWaveform.CreateShape(Dummy : Integer) : TShape;
Differences between DelphiScript and Object Pascal In this section, the differences between DelphiScript and Object Pascal of Borland Delphi 32 bit versions will be covered in detail. The scripting system uses untyped DelphiScript language therefore there are no data types in scripts.
Although you can declare variables and their types and to specify the types for functions/procedures or methods' parameters for readability, DelphiScript converts undeclared variables on the fly (when a script is being executed).
You cannot define records or classes for example.
Delphiscript Variables All variables in a script are always of Variant type, thus, typecasting of variables is ignored. Types in variables declaration are ignored and can be skipped, so these declarations are correct: Var
a : Integer;
Var
b : Integer;
Delphi Script Reference
16 TR0120 (v1.1) April 26, 2005
Var
c, d;
Types of parameters in procedure/function declaration are ignored and can be skipped. For example, this code is correct: Function Sum(a, b) : Integer;
Begin
Result := a + b;
End;
In general, you can use variants to store any data type and perform numerous operations and type conversions. A variant is type-checked and computed at run time. The compiler won't warn you of possible errors in the code, which can be caught only with extensive testing. On the whole, you can consider the code portions that use variants to be interpreted code, because, many operations cannot be resolved until run time. This affects in particular the speed of the code.
Now that you are aware of the use of the Variant type, it is time to look at what it can do. Basically, once you've declared a variant variable such as the following: Var
V;
Begin
// you can assign to it values of several different types:
V := 10;
V := 'Hello, World';
V := 45.55;
End;
Once you have the variant value, you can copy it to any compatible-or incompatible-data type. If you assign a value to an incompatible data type, Delphiscript interpreter performs a conversion, if it can. Otherwise it issues a run-time error. In fact, a variant stores type information along with the data, and thus a Delphiscript is slower than a Borland Delphi compiled code.
Functions / procedures inside a function or procedure It is recommended that you write standalone functions or procedures (recursive procedures/functions are permitted although). This function snippet is not recommended. Function A
Function B
Begin
// blah
End;
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 17
Begin
B;
End;
Recommended function structure Function B
Begin
// blah
End;
Function A
Begin
B;
End;
Result keyword You can't use the function name to set the return value within a function block, use Result to do so.
Example Function Foo : String;
Begin
Result := ‘Foo Foo’;
End;
Nested Routines Nested routines are supported but you can't use variables of top level function from the nested one.
Array elements Type of array elements is ignored and can be skipped so these declarations are equal: Var
x : array [1..2] of double;
Var
x : array [1..2];
You cannot declare array types but you can declare arrays to variables Illegal example Type
TVertices = Array [1..50] Of TLocation;
Delphi Script Reference
18 TR0120 (v1.1) April 26, 2005
Var
NewVertices : TVertices;
Legal example Var
NewVertices : Array [1..50] of TLocation;
Open array declaration The Open array declaration is not supported.
Case keyword The case keyword can be used for any type. So you can write Case UserName of
'Alex', 'John' : IsAdministrator := true;
'Peter' : IsAdministrator := false;
Else
Raise('Unknown user');
End;
Class declarations You cannot define new classes, but you can use existing Delphi Script classes and instantiate them. For example TList and TStringList classes can be created and used in your scripts.
See also TList
TStringList
CreateObject function The CreateObject function can be used to create objects that will be implicitly freed when no longer used. So instead of Procedure Proc;
Var
l;
Begin
l := TList.Create;
Try
// do something with l
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 19
Finally
L.Free;
End;
End;
you can write Procedure Proc;
Var
l;
Begin
l := CreateObject(TList);
// Do something with l
End;
See also CreateObject keyword
Raise exceptions Raise can be used without parameters to re-raise the last exception. You can also use Raise with string parameter to raise the exception with the specified message string. The Exception objects are not supported, because the On keyword is not supported.
Example Raise(Format('Invalid value : %d', [Height]));
See also Try keyword
Finally keyword
Raise keyword
ThreadVar The Threadvar keyword is treated as Var. Note that in Object Pascal, the variables declared using Threadvar have distinct values in each thread.
Set operator The Set operator In is not supported. You can use InSet to check whether a value is a member of set.
For example, If InSet(fsBold, Font.Style) then
ShowMessage('Bold');
Delphi Script Reference
20 TR0120 (v1.1) April 26, 2005
Note, that set operators '+', '-', '*', '<=', '>=' don't work correctly. You have to use logical operators.
Example ASet := BSet + CSet; should be changed to
ASet := BSet or CSet;
The [...] set constructors are not supported. You can use MkSet to create a set.
Example Font.Style := MkSet(fsBold, fsItalic);
See also MkSet keyword
InSet keyword
Operators ^ and @ operators are not supported.
Directives The following directives are not supported (note that some of them are obsolete and aren't supported by Delphi too): absolute, abstract, assembler, automated, cdecl, contains, default, dispid, dynamic, export, external, far, implements, index, message, name, near, nodefault, overload, override, package, pascal, private protected, public, published, read, readonly, register, reintroduce, requires, resident, safecall, stdcall, stored, virtual, write, writeonly.
Note, the "in" directive in uses clause is ignored.
Ignored Keywords The interface, implementation, program and unit keywords are ignored in Delphiscript. The scripts can have them but they have no effect but these keywords can enhance the readability of scripts.
Unsupported Keywords
The following keywords are not supported in Delphiscript:
The functions from the Borland Delphi's Windows unit (windows.pas file) are not supported (for example the RGB function is not supported).
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 21
Delphi Script Error Codes
Error Description
%s expected but %s found
Wrong string used in the script..
%s or %s expected Wrong string used in the script.
Function %s is already defined
Multiple instances of functions with same name in the code are not permitted. Rename the other functions that have the same name.
Unknown identifier: %s Unknown identifier. Need to declare this identifier first before using this identifier.
Unknown variable type during writing program
The script has a Variable type which is not valid or unknown.
Unit %s already defined Multiple instances of same unit names are not permitted. Ensure script unit names are unique.
Unit declaration error The unit declaration is not properly defined.
Function %s not found Missing function in the script.
Link Error Delphi script is unable to link the script to the required internal components.
Label <%s> already defined
Multiple instances of the same label exist in the script. Ensure labels are unique in the script.
Error in declaration block The declaration block is not defined correctly.
Label <%s> not defined The Goto label is not defined.
Variable <%s> already defined
Multiple instances of the same variables exist in the script. Ensure variables are unique.
Error in variable declaration block
Error exists in the variable declaration block. Wrong declarations or declarations not recognized by the scripting system.
Variable <%s> not defined
Variable was not defined, so the scripting system cannot define this variable.
Method declaration error Method signature is illegal.
Method parameters declaration error
Wrong parameters used for the method.
Properties are not Properties of an object not recognized by the scripting system.
Delphi Script Reference
22 TR0120 (v1.1) April 26, 2005
Error Description
supported
Only class declarations allowed
Declarations other than classes were attempted to be declared.
%s declaration error Declaration error exists in the script.
Syntax error at Line: %d Char: %d'#13#10'%s
A syntax error has occurred on the script - illegal statement, missing character or unrecognized keyword.
Bad identifier name <%s> Invalid identifier name such as duplicated identifier name. Redefine the identifier name.
Bad identifier <%s> Invalid identifier. Redefine a new identifier
Invalid function usage Function not used correctly in the script - such as invalid parameters.
Invalid procedure usage Procedure not used correctly in the script - such as invalid parameters.
Hex constant declaration error
Hex constant value not declared correctly.
Compile before run The script needs to be compiled first before it can be executed. An internal error.
Real constant declaration error
Real type constant declaration error.
String constant declaration error
String type constant declaration error.
Unsupported parameter type
Unknown parameter type as reported by the scripting system.
Variable Result not found for %s
Variable value result not found for the specified string in the script.
Procedure %s not found Missing procedure in the script.
Parameter %S not found Missing parameter in the script.
Unknown reader type An internal error.
Wrong number of params The same procedure or function declared and implemented differently. Check the parameters between the two.
One of the params is not a valid variant type
One of the parameters of a method, function or procedure does not have a correct variant type.
Property does not exist or An attempt to set a value to the read only property or a property does
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 23
Error Description
is readonly not exist.
Named arguments are not supported
Arguments used for the procedure or function not valid for the script.
Parameter not found Missing parameter value.
Parameter type mismatch Wrong parameter type used.
Unknown interface This interface is not declared or defined.
A required parameter was omitted
Missing parameter required for the method, function or procedure.
Unknown error Delphi Script has detected an unknown script error that is not defined in the internal errors table.
Invalid operation code Delphi Script has detected an invalid operation code.
Delphi Script Reference
TR0120 (v1.0) December 01, 2004 24
DelphiScript Keywords The scripting system supports the DelphiScript language which is very similar to Borland Delphi (TM)'s Object Pascal language. The key difference is that, DelphiScript is a typeless or untyped scripting language. You can still declare variables with type identifiers within scripts for readability.
In this section, DelphiScript keywords are outlined with concise information and some have examples.
Tips There is no need to have a "Uses" keyword in your script because the units such as the Workspace Manager unit and the Borland Delphi run time library units that are supported by the scripting system are automatically available in your scripts. Note, most of the functions from the Windows unit (windows.pas file) are not supported (for example the RGB function is not supported).
There are a few identifiers or functions that are not supported. Refer to the Differences between DelphiScript and Object Pascal for further information.
Reserved words in DelphiScript
A, B Abs, And, APpend, ArcTan, AssignFile, Array, Begin, Break
S, T SetLength, Shl, SHr, Sin, Sqr, Sqrt, String, Succ, Then, To, Trunc, Try, Type,
U, W, X Unit, Until, UpperCase, Uses, Var, While, With, Write, Writeln, Xor
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 25
Abs
Declaration Abs (number : integer);
Description Returns the absolute value of a given number as a parameter.
And
Declaration And operator performs a logical/bitwise and.
Description The and operator performs a logical and if the operators are of boolean type or a bitwise and if the operators are integers.
Example of a boolean and evaluation Var
I, J : Integer
Begin
I := $F0;
J := $8F;
ShowMessage(IntToStr(I and J));
End;
Example of a logical and evaluation Var
S : String;
Begin
S := '';
If (Length(S) > 0) and (S[1] = 'X') Then Delete(S,1,1);
End;
See also Or and Xor procedure.
Append
Declaration Append (var F : TextFile)
Delphi Script Reference
26 TR0120 (v1.1) April 26, 2005
Description This procedure opens an existing file with write access and positions the file pointer at the end of the file, ready to append new text to the existing file. If the file does not exist, this procedure will result in an error. If the file is already open when the procedure call is made, it will be closed and then reopened.
See also AssignFile procedure.
ArcTan
Declaration Function ArcTan(Number : (X: Extended): Extended;
Description Returns the arctangent of a given number where X is a real-type expression that gives an angle in radians.
See also Append, CloseFile, ChDir, MkDir, Read, ReadLn, RmDir, Write and Writeln functions.
Array
Declaration Array [index range];
Description Since Delphi Script language is a type-less language, you only need to specify the size or range of an array. You can still define what type of elements the array can hold, but it is not necessary. The Open array declaration is not supported.
Example var x : array [1..2];
Begin
Declaration Begin
statement
End;
Description The begin keyword starts a block in the script. A block is the main body of a script and can enclose any number of statements and can be used anywhere a single statement is required, such as the body of a conditional or loop statement.
Example Var
Test : Integer;
Delphi Script Reference
28 TR0120 (v1.1) April 26, 2005
Begin
Test := Test + 4;
ShowMessage(IntToStr(Test));
End;
See also End keyword.
Break
Declaration Break;
Description The break keyword jumps out of a loop, similar to the goto statement.
See also Continue, For, Repeat, While, Goto and Exit keywords.
Case
Declaration Case expression Of
Value range : Expression;
Else Expression;
End;
Description The case statements select one branch out of many possible branches depending on the value of the expression.
If you have very complex if statements, at times you can replace them with case statements. A case statement in an expression is used to select a value, a list of possible values, or a range of values. Any types can be used in a Case statement because DelphiScript is an un-typed language. Case statements can have an else statement that is executed if none of the labels correspond to the value of the selector (within the Case Of condition).
Description The ChDir procedure changes the working directory and drive to the path specified in the Directory argument. If ChDir cannot set the directory for any reason, it reports an I/O error.
See also GetDir, MkDir, RmDir procedures.
Chr
Declaration procedure Chr(Value : Integer);
Description The Chr procedure returns the character for a specified value.
See also Copy, Delete, Insert, Length, Ord procedures.
CloseFile
Declaration
Delphi Script Reference
30 TR0120 (v1.1) April 26, 2005
procedure CloseFile(var f: file);
Description Call CloseFile to close a file associated with the f parameter.
Example AssignFile(OutputFile,NewFileName);
Rewrite(OutputFile);
AssignFile(InputFile,OldFileName);
Reset(InputFile);
Try
While not EOF(InputFile) do
Begin
Readln(InputFile,Line);
For I := 1 to Length(Line) Do
Line[I] := UpperCase(Line[I]);
Writeln(Outputfile, Line);
End;
Finally
CloseFile(InputFile); CloseFile(OutputFile); End;
Close;
See also Append
AssignFile
ChDir
MkDir
Read
ReadLn
RmDir
Write
Writeln functions.
Const
Declaration Const
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 31
Name = expression;
Name ; Type = Expression;
Description The Const keyword specifies any constant valued expression as the value of a constant and also declare a sub-routine parameter as const. A sub-routine cannot modify a const parameter.
Continue
Declaration Procedure Continue;
Description The Continue procedure returns control to the next iteration of For, While or Repeat statements. The Continue statement jumps over the body of a loop, similar to the goto statement. That is, the continue statement causes the executing script to pass to the next iteration in the current For, While or Repeat loop.
Example Var
F: File;
i: Integer;
Begin
For i := 0 to (FileListBox1.Items.Count - 1) do
Begin
Try
If FileListBox1.Selected[i] Then
Begin
If not FileExists(FileListBox1.Items.Strings[i]) then
Description The copy function returns a substring of a string, ie it creates a copy of part of a string. The result is a new string. The new string starts with the element at starting index in source. The new string contains up to count elements.
See also Chr, Delete, Insert, Length procedures.
Cos
Declaration function cos(number : extended) : extended;
Description The Cos function computes and returns the cosine of the number parameter which is an angle in radians.
See also ArcTan, Sin functions.
CreateObject
Declaration Function CreateObject(object) : Object;
Description The CreateObject function takes a variable number of parameters. The first one is always the object class, and the rest are parameters passed to the constructor. In the case of TOpenDialog class from the Borland Delphi Run Time Library, its constructor (Create) has one parameter, so the correct syntax would be:
Description The Delete procedure removes Count characters from a string starting at StartingIndex. If Count is more than the number of characters remaining in the string, Delete deletes the rest of the string, starting from StartingIndex.
See also
Delphi Script Reference
34 TR0120 (v1.1) April 26, 2005
Chr, Copy, Insert, Length procedures.
Div
Declaration dividend div divisor
Description The Div operator performs integer division which discards fractional results without rounding. If the divisor is zero, DelphiScript reports an error.
See also Mod and / Operators.
Do
Declaration • for variable := expression1 to expression2 do statement
• while expression do statement
• with expression do statement.
Description The do keyword is part of DelphiScript's For, While and With statements.
Example For i := 0 To AnIndex - 1 Do
S := S + #13 + AString;
See also For, To, While, With, DownTo keywords.
DownTo
Declaration for variable := expression1 downto expression2 do statement.
Description Use downto in a for loop to count down.
See also for, do keywords.
Else
Declaration
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 35
• if condition then statement else statement
• try statement except exception else statement end
• case expression of else end;
Description The else keyword introduces the catch all part of several statements. Note that the else part of an if statement is followed by a single statement, but the else part of the try-except and case statements can have multiple statements.
See also If, Then, Try, Case keywords.
Eof
Declaration function Eof(var F : TextFile) : Boolean
Description The Eof function returns true if the file F is at the end of the file.
Example AssignFile(OutputFile,NewFileName);
Rewrite(OutputFile);
AssignFile(InputFile,OldFileName);
Reset(InputFile);
Try
While not EOF(InputFile) do Begin
Readln(InputFile,Line);
For I := 1 to Length(Line) Do
Line[I] := UpperCase(Line[I]);
Writeln(Outputfile, Line);
End;
Finally
CloseFile(InputFile);
End;
Close;
See also Append, CloseFile, ChDir, Eoln, MkDir, Read, ReadLn, Reset, RmDir, Write and Writeln functions.
Delphi Script Reference
36 TR0120 (v1.1) April 26, 2005
Eoln
Declaration Function Eoln(var F : textfile) : boolean;
Description The Eoln function returns true, if the file F is at the end of a line or at the end of the file. Eoln interprets a carriage return (#13) as the end of a line.
See also Append, CloseFile, ChDir, EOF, MkDir, Read, ReadLn, Reset, RmDir, Write and Writeln functions.
Description The end keyword ends a block or a multiple part such as declarations, case statements and so on.
See also Begin, Case, Try keywords.
Erase
Declaration procedure Erase(Var F : File);
Description The Erase Deletes the file that is assigned to F. The file should be closed but with a filename assigned to it.
See also Append, CloseFile, ChDir, Eoln, MkDir, Read, ReadLn, Reset, RmDir, Write and Writeln functions.
Except
Declaration try statements except statements end;
Description Use Try-Except blocks to handle exceptional cases for example to catch specific exceptions and do something useful with them, such as log them in an error log or create a friendly dialog box. Since the On keyword is not supported in DelphiScript, thus use the the Raise statement inside the Except block and only report a textual message.
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 37
Example Try
X := Y/Z;
Except
Raise(‘A divide by zero error!’);
End;
See also Try, Finally, End keywords.
Exit
Declaration Exit;
Description Call the Exit procedure to return immediately from a subroutine. If you call exit within a try finally block, the finally sub-block runs before the subroutine returns. If you call the Exit outside a subroutine, the script is ended.
See also Break, Goto, Try keywords.
Exp
Declaration function Exp(x : extended) : extended;
Description The Exp function computes ex.
See also Ln function.
File
Declaration Var
AFile : File;
AFile : TextFile;
Description A file is a binary sequence of some type. A file contents are usually stored in a persistent storage such as a hard disk. Before a file variable can be used, it must be associated with an external file through a
Delphi Script Reference
38 TR0120 (v1.1) April 26, 2005
call to the AssignFile procedure. An external file is typically a named disk file. Once the association with an external file is established, the file variable must be opened to prepare it for input or output.
An existing file can be opened via the Reset procedure and a new file can be created and opened via the Rewrite procedure. To read contents of a file, use Read/ReadLn statements and to write contents to a file, use Write/Writeln statements. When a script completes processing the file, it must be closed using CloseFile procedure.
Example Var
InputFile : TextFile;
OutputFile : TextFile;
I : Integer;
Line : String;
Begin
AssignFile(OutputFile,eConvertedFile.Text);
Rewrite(OutputFile);
AssignFile(InputFIle,eOriginalFIle.Text);
Reset(InputFile);
Try
While not EOF(InputFile) do
Begin
Readln(InputFile,Line);
For I := 1 to Length(Line) Do
Line[I] := UpperCase(Line[I]);
Writeln(Outputfile, Line);
End;
Finally
CloseFile(InputFile);
CloseFile(OutputFile);
End;
End;
See also Append, AssignFile, CloseFile, ChDir, MkDir, Read, ReadLn, RmDir, Write and Writeln functions.
Description The finally keyword starts the finally part of a try-finally block. The statements in the finally block always run, no matter how control leaves the try block exception, exit or break. The use of try-finally block is recommended when dealing with creation/destruction of objects and File IO.
See also Try, End, Raise keywords.
For
Declaration • for variable := expression1 to expression2 do statement
• for variable := expression1 downto expression2 do statement
Description A for loop evaluates the expressions that specify the limits of this loop, then performs the loop body repeatedly via the loop control variable which is updated after each iteration.
Example For i := 0 to AnIndex - 1 Do
Begin
S := S + #13 + AString;
End;
ShowMessage(S);
See also To, DownTo, Do, Repeat, While keywords.
Format
Declaration function Format(const Format: string; const Args: array of const): string;
Description The format function assembles a formatted string from a series of arrays. Format specifiers fetch arguments from the argument list and apply formatting to them. Format specifiers have the following form: "%" [index ":"] ["-"] [width] ["." prec] type. Refer to Borland Delphi documentation for further details.
Delphi Script Reference
40 TR0120 (v1.1) April 26, 2005
Example Format('%*.*f', [8, 2, 123.456])
is the same as Format('%8.2f', [123.456]).
Forward
Declaration subroutine header; forward;
Description This Forward directive lets you declare a function or procedure before you call it by declaring the header (name, parameters, and return type) with the forward directive.
Frac
Declaration function frac(x : extended) : extended;
Description The frac function returns the fractional part of a floating point number.
See also Int, Round and Trunc functions.
Function
Declaration function name (parameters) : return type;
Description A function is a subroutine that returns a value. Note that pointers to functions are not permitted in scripts, ie you cannot define functional types. Variables declared inside a function are not accessible outside this procedure.
Example Function TestFunc(Min, Max : integer) : integer;
Begin
Result := Random(Max - Min +1);
End;
GetDir
Declaration
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 41
procedure getdir(drive : byte; var directory : string);
Description The GetDir procedure stores in Directory the default directory for the drive specified by the drive parameter. If Drive is 1 for A drive through 26 for Z: drive, the GetDir retrieves the default directory for that drive.
The value stored in the Directory parameter always begins with the drive letter eg X:\Program Files
See also Append, AssignFile, CloseFile, ChDir, MkDir, Read, ReadLn, RmDir, Write and Writeln functions.
Goto
Declaration goto label
Description The goto statement transfer control to the given label. The label can be any identifier or a digit string with up to four digits.
Example Label StartHere;
// code
StartHere: //do anything;
Goto StartHere;
See also Label keyword.
If
Declaration • if condition then statement;
• if condition then statement1 else statement2;
Description The condition for the If keyword must be a boolean expression. The Else keyword is optional.
Example If X > Y Then
If A > B Then
Delphi Script Reference
42 TR0120 (v1.1) April 26, 2005
ShowMessage('X>Y and A > B');
Else
ShowMessage('X>Y and A <=B');
End;
See also And, Begin, Or, Then, Else keywords.
Insert
Declaration Procedure insert(const ins: string; var str: string; index: integer);
Description The insert procedure inserts the string ins into the string str at the position index. If Index <= 1 then the Ins string is inserted at the beginning of str. If index is past the end of the string, it is appended to the end of str.
See also Copy, Chr, Delete, Length procedures.
InSet
Declaration Function InSet(setA, setB) : Boolean;
Description Since Object Pascal’s Set and In keywords are not supported in Delphi Script, to overcome this limitation, you can use these two functions: MkSet and InSet. You should use logical operations to include or exclude elements to set. InSet - this function is used as substitution of Object Pascal’s In operator. A in B is equal to InSet(A, B).
Example If InSet(A,B) then
ShowMessage(‘A is in B set’)
Else
ShowMessage(‘A not in B set’);
Notes: The set operators '+', '-', '*', '<=' and '>=' don't work correctly in Delphi Script. You should use logical operators instead. For example,
ASet := BSet + CSet;
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 43
should be changed to
ASet := BSet or CSet;
in order to achieve the desired result in your script.
See also MkSet procedure.
Int
Declaration Function Int(X : extended) : extended;
Description The Int function truncates a extended type number by discarding its fractional part (rounds towards zero).
See also Frac, Round and Trunc functions.
Interface
Declaration Interface
// Globally unique identifier string.
Methods
Properties
End;
Description The interface keyword enables you to have access to an existing object in memory and invoke the object's methods. An interface can only consist of properties and methods - no data. Since interfaces cannot contain data, their properties must write and read to and from methods. Most importantly interfaces have no implementation, as they only define a contract (to an existing object in memory).
Think of an interface as a contact point to an existing object in computers memory, and you have the ability to read/write data through properties of the interface. The interface requests for data from its associated object.
Delphi Script is a type-less language, therefore you cannot define new types such as new records, arrays or classes and associated interfaces as well.
Beware of the other use of the Interface keyword which is used for the Interface / Implementation sections of a Borland Delphi's unit. These Interface/Implementation keywords can be used in scripts but they are essentially ignored when a script is being executed in Altium Designer.
See also
Delphi Script Reference
44 TR0120 (v1.1) April 26, 2005
Client API
Nexus API
PCB API
Schematic API
Workspace Manager API
Label
Declaration label digits, identifier, ...;
Description The label keyword declares one or more labels. A label can be digit string with up to four digits or an identifier. A label can be used in the same block to identify a statement as the target of a goto statement.
Example Label StartHere;
// code
StartHere: //do anything;
Goto StartHere;
See also Goto keyword.
Length
Declaration function length( const s: string) : integer;
Description The length function returns the number of elements in a string.
Example Var
I : Integer;
Begin
For I := 1 To Length(s) Do
S[I] := UpperCase(S[i]);
End;
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 45
See also Copy, Chr, Delete procedures.
Ln
Declaration function Ln(x : extended) : extended;
Description The Ln function returns the natural logarithm of the parameter x.
Description The MkDir procedure when invoked creates a directory. You can include or omit a trailing backslash character in the directory name.
See also Append, AssignFile, CloseFile, ChDir, MkDir, Read, ReadLn, RmDir, Write and Writeln functions.
MkSet
Declaration Function MkSet(setA, setB, ...) :[..];
Description Since Object Pascal’s Set and In keywords are not supported in Delphi Script, to overcome this limitation, you can use these two functions: MkSet and InSet. You should use logical operations to include or exclude elements to set.
MkSet - this is a set constructor. It has variable number of arguments. You can write like Font.Style = MkSet(fsBold,fsItalic)
Notes The set operators '+', '-', '*', '<=' and '>=' don't work correctly in Delphi Script. You should use logical operators instead. For example, ASet := BSet + CSet;
should be changed to
Delphi Script Reference
46 TR0120 (v1.1) April 26, 2005
ASet := BSet or CSet;
in order to achieve the desired result in your script.
Declaration Integer expression mod integer expression.
Description The mod operator performs an integer modulus or remainder operation. The result of A mod B is A - (A div B) * B.
See also
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 47
Div function.
Nil
Declaration const nil = pointer(0);
Description The nil keyword is a special pointer value that is guaranteed to be distinct and pointing to nothing.
Not
Declaration • not boolean expression
• not integer expression.
Description The not operator performs a negation. If the operand has type boolean, the negative is a logical negation. Not False = True and not true = false. If the operand is an integer, the not operator performs a bitwise negation of each bit in the integer value, ie a complement operation.
See also Exp function.
Of
Declaration case expression of
selector: expression1
...
end
Description The Of keyword is used for the case statement.
See also Case statement.
Or
Declaration • boolean expression or boolean expression
• integer expression or integer expression
Delphi Script Reference
48 TR0120 (v1.1) April 26, 2005
Description The or operator performs a logical or if the operands are of boolean type or a bitwise or if the operators are integers. A logical or is false only if both operands are false otherwise the it is true when at least one operand is true.
See also And, Not, Shl, Shr, Xor keywords.
Ord
Declaration function Ord(C : Char) : Integer;
Description The Ord function returns the ordinal value of an ordinal type expression.
Description The Pos function returns the index of the first character of a specified substring parameter in a str string parameter.
See also Chr, Delete, Insert, Length procedures.
Pred
Declaration function pred (const value) : enumerated value;
Description The Pred function returns the predecessor of an ordinal value.
See also Chr, Ord, Succ functions.
Procedure
Declaration
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 49
• Procedure name;
• Procedure Name (Parameter, ...);
Description The procedure keyword declares a subroutine that does not have a return type. Variables declared inside a procedure are not accessible outside this procedure.
Note this keyword can be used but it is ignored by the scripting system.
Example Procedure TestRand(Var Rand: Integer; Max : Integer);
Begin
Rand := Random(Max);
End;
See also Function keyword.
Program
Declaration Program Name;
declarations...
Block.
Description The program keyword begins a script. The file extension for a script is .pas. Note this keyword can be used but it is ignored by the scripting system.
See also Function keyword.
Raise
Declaration Raise statement;
Description The raise keyword is related to the Try keyword. The Raise keyword can be used without parameters to re-raise the last exception. It can also be used with a string parameter to raise an exception using a specific message.
Example Raise(Format('Invalid Value Entered : %d', [Height]));
Delphi Script Reference
50 TR0120 (v1.1) April 26, 2005
Note, the On keyword is not supported, thus you cannot use Exception objects in your scripts.
Random
Declaration • function random : extended;
• function random(limit : integer) : integer;
Description The random function returns a pseudorandom number. Without a parameter, it returns a extended value in the range 0 <= result < 1. If an integer parameter is passed in, then it returns an integer in the range 0 <= result <= limit.
Call Randomize once to start the sequence of pseudorandom numbers at a different number each time you run the script.
See also Randomize keyword.
Randomize
Declaration procedure randomize;
Description Call Randomize once at the start of a script to start the sequence of pseudo-random numbers at a different number each time you run the script. Do not call randomize more than once in the same script.
See also Randomize keyword.
Read
Declaration • procedure read(var F : File; var variable; ...);
• procedure read(var F : TextFile, var Variable; ....);
Description The read procedure reads one or more values from a file into one or more variables.
See also Append, AssignFile, CloseFile, ChDir, MkDir, ReadLn, RmDir, Write and Writeln functions.
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 51
Readln
Declaration • procedure readln(var F : File; var variable; ...);
• procedure readln(var F : TextFile, var Variable; ....);
Description The readln procedure reads one or more values from a file into one or more variables and then skips to beginning of next line in the text file.
Example AssignFile(OutputFile,NewFileName);
Rewrite(OutputFile);
AssignFile(InputFile,OldFileName);
Reset(InputFile);
Try
While Not EOF(InputFile) do
Begin
Readln(InputFile,Line); For I := 1 to Length(Line) Do
Line[I] := UpperCase(Line[I]);
Writeln(Outputfile, Line);
End;
Finally
CloseFile(InputFile);
End;
Close;
See also Append, AssignFile, CloseFile, ChDir, MkDir, Read, ReadLn, Reset, RmDir, Write and Writeln functions.
Repeat
Declaration repeat
statements;
until boolean expression
Description
Delphi Script Reference
52 TR0120 (v1.1) April 26, 2005
The statements inside a Repeat Until block are executed repeatedly until the boolean expression is true.
Example Repeat
Write('Enter a value (0..9): ');
ShowMessage(IntToStr(I));
Until (I >= 0) and (I <= 9);
See also Until keyword
Reset
Declaration • procedure reset (var F : TextFile);
• procedure reset(var F : File);
Description The Reset procedure opens an existing file.
Example AssignFile(OutputFile,NewFileName);
Rewrite(OutputFile);
AssignFile(InputFile,OldFileName);
Reset(InputFile); Try
While not EOF(InputFile) do Begin
Readln(InputFile,Line);
For I := 1 to Length(Line) Do
Line[I] := UpperCase(Line[I]);
Writeln(Outputfile, Line);
End;
Finally
CloseFile(InputFile);
CloseFile(OutputFile);
End;
Close;
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 53
See also Append, AssignFile, CloseFile, ChDir, MkDir, Read, ReadLn, Reset, RmDir, Write and Writeln functions.
Result
Declaration Var result : Function return type;
Description Every function in a script must use the Result keyword to return a resultant value. The variable type is the return type of the function.
See also Function keyword.
Rewrite
Declaration • procedure Rewrite(var F: TextFile);
• procedure Rewrite(var F: File);
Description The Rewrite procedure creates and opens a new file. This new file is ready for writing.
Description The RmDir procedure removes an empty directory.
See also Append, AssignFile, CloseFile, ChDir, MkDir, Read, ReadLn, RmDir, Write and Writeln functions.
Round
Declaration function round (x : extended) : integer;
Description The Round function rounds off a floating type value to an itneger.
See also Frac, Int, Trunc functions.
SetLength
Declaration procedure setlength(var s : string; length : integer);
Description The SetLength procedure changes the size of a string.
See also Chr, Delete, Insert, Length, Pos procedures.
Shl
Declaration value shl bits
Description
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 55
The shl operator performs a left shift of an integer value by Bits bit positions. The vacated bits are filled on the right with zero bits.
See also And, Not, Or, Shr, Xor keywords.
Shr
Declaration value shr bits
Description The shr operator performs a right shift of an integer value by Bits bit positions. The vacated bits are filled on the left with zero bits.
See also And, Not, Or, Shl, Xor keywords.
Sin
Declaration function sin(number : extended) : extended;
Description The Sin function computes and returns the sine of the number parameter which is an angle in radians.
See also ArcTan, Cos functions.
Sqr
Declaration function Sqr(X : extended) : extended;
Description The Sqr function returns the square of the X parameter.
See also Sqrt function.
Sqrt
Declaration function Sqrt(X : extended) : extended;
Description
Delphi Script Reference
56 TR0120 (v1.1) April 26, 2005
The Sqrt function returns the positive square root of the X parameter.
See also Sqr function.
String
Declaration • type string;
• type Name = string[Constant]
Description The string keyword represents the string type.
Succ
Declaration function succ (const value) : enumerated value;
Description The Succ function returns the successor of an ordinal value.
See also Chr, Ord, Pred functions.
Then
Declaration If expression then statement.
Description The Then keyword is part of an If statement.
See also If keyword.
To
Declaration For variable := expression1 to expression2 do statement.
Description The to keyword is part of a for lop that counts up.
Example
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 57
For i := 0 to AnIndex - 1 do
S := S + #13 + AString;
See also Downto and For keywords
Trunc
Declaration function trunc (X : extended) : integer;
Description The Trunc function truncates a floating point value by discarding the fractional part (round towards zero). Unlike Int, trunc returns an integer result.
Description The try keyword introduces a try-except statement or a try-finally statement. These two statements are related but serve different purposes.
Try Finally The statements in the finally block are always executed no matter how control leaves the try block exception, Exit or break. Use try-finally block to free temporary objects and other resources and to perform clean up activities. Typically you do not need more than one try-finally statement in a subroutine.
Example Reset(F);
Try
... // process file F
Finally
CloseFile(F);
End;
Try Except
Delphi Script Reference
58 TR0120 (v1.1) April 26, 2005
Use try-except to handle exceptional cases for example to catch specific exceptions and do something useful with them, such as log them in an error log or create a friendly dialog box. Since the On keyword is not supported in DelphiScript, so you can use the Raise statement inside the Except block.
Example Try
X := Y/Z;
Except
Raise(‘A divide by zero error!’);
End;
See also Raise keyword.
Type
Declaration Type Name = type declaration ...
Description The Type keyword declares the type for a variable. Since Delphi Script is a typeless language, it is not necessary for you to declare variables of specific type. You can do so for the sake of readability in your scripts. All variables in a script are always of Variant type. The major limitation in writing scripts is that you cannot declare records or classes.
Finally, using typecasting is ignored in scripts. Types in variables declaration are ignored and can be skipped, so these declarations are correct:
Example var a : integer;
var b : integer;
var c, d;
Types of parameters in procedure/function declaration are ignored and can be skipped. For example, this code is correct: Function sum(a, b) : integer;
Begin
result := a + b;
End;
In general, you can use variants to store any data type and perform numerous operations and type conversions. A variant is type-checked and computed at run time. The compiler won't warn you of possible errors in the code, which can be caught only with extensive testing. On the whole, you can consider the code portions that use variants to be interpreted code, because, many operations cannot be resolved until run time. This affects in particular the speed of the code.
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 59
Now that you are aware of the use of the Variant type, it is time to look at what it can do. Basically, once you've declared a variant variable such as the following:
Example Var
V
Begin
// you can assign to it values of several different types:
V := 10;
V := 'Hello, World';
V := 45.55;
End;
See also Var keyword
Unit
Declaration • Unit Name;
interface
declarations
implementation
declarations
statements
Initialization
statements
finalization
statements.
end.
• Unit Name;
interface
declarations
implementation
declarations
statements
begin
statements
Delphi Script Reference
60 TR0120 (v1.1) April 26, 2005
end.
The unit keyword introduces a unit which is the basic module for a script. Note this keyword can be used but it is ignored by the scripting system.
See also Function, Program keywords.
Until
Declaration Repeat
Statements;
Until boolean expression
Description The until keyword marks the end of the Repeat - Until block. The statements inside a Repeat Until block are executed repeatedly until the boolean expression is true.
Example Repeat
Write('Enter a value (0..9): ');
ShowMessage(IntToStr(I));
Until (I >= 0) and (I <= 9);
See also Repeat keyword
UpperCase
Declaration Function (str : string) : String
Description The UpperCase function converts a string to upper case.
See also Chr, Delete, Insert, Length, Pos procedures.
Uses
Declaration Uses Unit Name, ...;
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 61
Description The uses keyword lists the names of units that are imported into the surrounding unit. The uses declaration is optional because the scripting system has supported units that are imported in the Altium Designer application. You can include the uses declaration for the sake of readability.
All units stored within the same project can access global variables from any of these units. Keep this in mind when you are declaring variables in your units within the same project.
At this time of writing, Altium Designer’s Client, Nexar, PCB, Schematic and WorkSpace Manager APIs,and Borland Delphi's SysUtils, Classes and other units are imported and available for use in scripts. So there is no need to declare these units in your scripts.
See also The Supported Borland Delphi Units topic in the DXP RTL Reference.
Var
Declaration Name : Type
Name : Type = Expression;
Delphi Script Variables All variables in a script are always of Variant type. Typecasting is ignored. Types in variables declaration are ignored and can be skipped, so these declarations are correct: Var a : integer;
Var b : integer;
Var c, d;
Types of parameters in procedure/function declaration are ignored and can be skipped. For example, this code is correct: Function sum(a, b) : integer;
Begin
Result := a + b;
End;
In general, you can use variants to store any data type and perform numerous operations and type conversions. A variant is type-checked and computed at run time. The compiler won't warn you of possible errors in the code, which can be caught only with extensive testing. On the whole, you can consider the code portions that use variants to be interpreted code, because, many operations cannot be resolved until run time. This affects in particular the speed of the code.
Now that you are aware of the use of the Variant type, it is time to look at what it can do. Basically, once you've declared a variant variable such as the following: Var
V;
Begin
Delphi Script Reference
62 TR0120 (v1.1) April 26, 2005
// you can assign to it values of several different types:
V := 10;
V := 'Hello, World';
V := 45.55;
End;
Array elements Type of array elements is ignored and can be skipped so these declarations are equal: Var x : array [1..2] of double;
Var x : array [1..2];
Illegal array example Type
TVertices = Array [1..50] Of TLocation;
Var
NewVertices : TVertices;
Legal array example Var
NewVertices : Array [1..50] of TLocation;
While
Declaration while expression do statement
Description The while statement repeatedly executes the statement while the expression is true.
See also Break, Continue, Do, For, Repeat keywords.
With
Declaration with expression do statement
Description The with statement adds a record, object, class or interface reference to the scope for resolving symbol names. Like a shorthand.
Normal version example Form.Canvas.Pen.Width := 2;
Form.Canvas.Pen.Color := clSilver;
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 63
With version example With Form.Canvas.Pen do
Begin
Width := 2;
Color := clSilver;
End;
See also Do keyword.
Write
Declaration procedure write(var F : File; var value, ...);
procedure write(var F : TextFile);
Description The write procedure writes one or more values to a file. you need to open a file first before writing to this file.
See also Append, AssignFile, CloseFile, ChDir, MkDir, Read, ReadLn, RmDir, Write and Writeln functions.
Writeln
Declaration procedure writeln(var F : File; var value, ...);
procedure writeln(var F : TextFile);
Description The Writeln procedure writes one or more values to a file and then adds a carriage return followed by a line feed (#13#10) to terminate this line. You need to open a file first before writing to this file.
Example AssignFile(OutputFile,NewFileName);
Rewrite(OutputFile);
AssignFile(InputFile,OldFileName);
Reset(InputFile);
Try
While Not EOF(InputFile) do
Begin
Readln(InputFile,Line);
Delphi Script Reference
64 TR0120 (v1.1) April 26, 2005
For I := 1 to Length(Line) Do
Line[I] := UpperCase(Line[I]);
Writeln(Outputfile, Line); End;
Finally
CloseFile(InputFile);
CloseFile(OutputFile);
End;
Close;
See also Append, AssignFile, CloseFile, ChDir, MkDir, Read, ReadLn, RmDir, Write and Writeln functions.
Description The xor operator performs an exclusive or on its operands. If the operands are of boolean type, it returns a boolean result: Ie True if the operands are different, and false if they are the same.
An integer xor operates on each bit of its operands, setting the result bit to 1 if the corresponding bits in both operands are different, and to 0 if both operands have identical bits. If one operand is smaller than the other, the smaller operand is extended with 0 in the left most bits.
See also And, Not, Shl, Shr, Xor keywords.
Delphi Script Reference
TR0120 (v1.0) December 01, 2004 65
Delphi Script statements A statement in Delphi Script is simple when it does not contain any other statements. Examples of simple statements are assignment statements and procedure calls.
Simple statements X := Y + 10; // assignment
ShowMessage(‘Hello World!’); // procedure call
A component statement consists of multiple statements. An example include
Compound statements Begin
If A > B Then ShowMessage(‘A is bigger’)
Else ShowMessage(‘B is bigger’);
A := 0;
B := 0;
End;
In Delphi script, when you are assigning values to variables, you use the colon-equal operator, :=. When you are testing for equality, you just use the equality operator, =.
In this section of the DelphiScript Statements:
Conditional statements
If Then statement
Case Of statement
With statement
For To Do loop
Repeat Until loop
While Do loop
Continue statement
Goto Label statement
Exit statement
Break statement.
Conditional statements Delphi Script has control statements which are statements that affect the flow of control or flow of execution within a script. The common conditional statement is If Then statement.
If Then statement The If..Then statement is used for conditional control. The syntax is:
If Condition Then
Delphi Script Reference
66 TR0120 (v1.1) April 26, 2005
Begin
// code here
End
Else
Begin
// code here
End;
Case of statement If you have very complex if statements, at times you can replace them with case statements. A case statement in an expression is used to select a value, a list of possible values, or a range of values. Any types can be used in a Case statement because DelphiScript is an untyped language. Case statements can have an else statement that is executed if none of the labels correspond to the value of the selector (within the Case Of condition).
Example 1 Case Char of
'+' : Text := 'Plus sign';
'-' : Text := 'Minus sign';
'*', '/': Text := 'Multiplication or division';
'0'..'9': Text := 'Number';
'a'..'z': Text := 'Lowercase character';
'A'..'Z': Text := 'Uppercase character';
else
Text := 'Unknown character';
End;
Example 2 Case UserName of
Jack', 'Joe' : IsAdministrator := true;
‘Fred' : IsAdministrator := false;
else
raise('Unknown User');
End;
With statement The with statement is a shorthand. When you need to refer to a record type variable (or an object), instead of repeating its name every time, you can use a with statement. For example, the code is as follows:
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 67
Normal version Form.Canvas.Pen.Width := 2;
Form.Canvas.Pen.Color := clSilver;
With version With Form.Canvas.Pen do
Begin
Width := 2;
Color := clSilver;
End;
For To Do loop The For..To .. Do statement provides a method for repeatedly looping through a block of code (that is one or more lines of code). The basic syntax is: For counter := start To end Do
Begin
// code here.
End;
For loops are often used to initialize an array. You can also control the direction for the counter in a For To Do loop by using the DownTo keyword instead to decrement the loop. Delphi Script provides the Break/Exit statement to exit a For To Do loop prematurely.
Repeat Until loop The Repeat statement is executed repeatedly until the Boolean expression is true. The Repeat statement is always executed at least once.
Example Repeat
Write('Enter a value (0..9): ');
ShowMessage(IntToStr(I));
Until (I >= 0) and (I <= 9);
While Do loop A while statement is similar to a repeat statement, except that the control condition is evaluated before the first execution of the statement sequence. Hence, if the condition is false, the statement sequence is never executed.
Example Randomize;
I := 0;
Delphi Script Reference
68 TR0120 (v1.1) April 26, 2005
While I < 1000 do
Begin
I := I + Random (100);
Add ('Random Number: ' + IntToStr (I));
End;
Continue statement The Continue statement jumps over the body of a loop, similar to the goto statement. The continue statement causes the executing script to pass to the next iteration in the current For, While or Repeat loop.
Example var
F: File;
i: Integer;
Begin
For i := 0 to (FileListBox1.Items.Count - 1) do begin
Try
If FileListBox1.Selected[i] Then
Begin
If not FileExists(FileListBox1.Items.Strings[i]) then
Goto Label statement The goto statement has the form goto label which transfers the script execution to the statement marked by the specified label. To mark a statement, you must first declare the label. Then precede the statement you want to mark with the label and a colon: label: statement.
A label can be any valid identifier. The label declaration and goto statement must belong to the same block within a script. Hence it is not possible to jump into or out of a procedure or function.
Example Label StartHere;
// code
StartHere: Beep;
Goto StartHere;
Exit statement The Exit statement returns immediately from a function or procedure. If you call exit from within a try-finally block, the finally part gets executed before the subroutine returns. If the Exit procedure is called from within the main body of the script, then execution of the script will terminate.
Example Begin
Server := SchServer;
If Server = Nil Then
Begin
ShowError('No SchServer started');
Exit;
End;
Break Statement The break statement causes the executing script to exit out of the current For, While or Repeat loop. Execution continues from the subsequent executable line of script after the current loop.
Example Var
S: string;
Begin
While True do
Begin
ReadLn(S);
Delphi Script Reference
70 TR0120 (v1.1) April 26, 2005
Try
if S = '' then Break;
WriteLn(S);
Finally
{ do something for all cases }
End;
End;
End;
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 71
Expressions and Operators An expression is a valid combination of constants, variables, literal values, operators and function results. Expressions are used to determine the value to assign to a variable, to compute the parameter of a function, or to test for a condition. Expressions can include function calls.
DelphiScript has a number of logical, arithmetic, Boolean and relational operators. Since these operators are grouped by the order of precedence which is different to the precedence orders used by Basic, C etc. For example, the AND and OR operators have precedence compared to the relational one.
For example if you write a<b and c<d, the Delphi Script will do the AND operation first, resulting in an error. To fix this problem, you have to enclose each of the < expression in parentheses: (a<b) and (c<d);
These operators listed below are the operators supported by Delphi Script.
Operators grouped by precedence Unary operators have the highest precedence
Not Boolean or bitwise NOT.
Multiplicative and Bitwise Operators
* Arithmetic multiplication.
/ Floating point division.
div Integer division.
mod modulus (reminder of integer division).
and Boolean or bitwise AND.
shl Bitwise left shift.
shr Bitwise right shift.
Additive Operators
+ Arithmetic addition, string concatenation.
- Arithmetic subtraction.
or Boolean or bitwise OR
xor Boolean or bitwise EXCLUSIVE OR.
Relational and Comparison Operators (lowest precedence)
= Test whether equal or not.
Delphi Script Reference
72 TR0120 (v1.1) April 26, 2005
<> Test whether not equal or not.
< Test whether less than or not.
> Test whether greater than or not.
<= Test whether less than or equal to or not.
>= Test whether greater than or equal to or not.
Note The ^ and @ operators are not supported by Delphi Script.
Delphi Script Reference
TR0120 (v1.0) December 01, 2004 73
DelphiScript Functions A few statements used by the DelphiScript language are covered here. The range of functions are covered in the FileIO routines, Math Routines, String Routines and Extension routines.
In this DelphiScript Functions Section:
• Calculating expressions with the evaluate function
• Passing parameters to functions and procedures
• Exiting from a procedure
• File IO routines
• Math routines
• String routines
• Extension routines
• Using sets in Delphi Script
• Using exception handlers
• Delphi Script Language.
Calculating expressions with the evaluate function The built in function Evaluate can be used to interpret a string as a script code during runtime of a script and execute the code contained in the string. For example, you can write script like Evaluate(ProcNames[ProcIndex]); and the procedure which name is specified in ProcNames[ProcIndex] will be called.
To calculate such an expression you can use Evaluate method, where expression is specified by Expr parameter. For example, you can calculate expressions like the following: Evaluate(‘2+5’);
Evaluate(‘((10+15)-5)/2*5’);
Evaluate(‘sin(3.1415926/2)*10’);
Evaluate(‘2.5*log(3)’);
Passing parameters to functions and procedures Both functions and procedures you define in a script can be declared to accept parameters. Additionally, functions are defined to return a value.
Types of parameters in procedure/function declaration are ignored and can be skipped. For example, this code is correct: Function sum(a, b) : integer;
Begin
result := a + b;
End;
Delphi Script Reference
74 TR0120 (v1.1) April 26, 2005
Exiting from a procedure Delphi Script provides Exit and Break statements, should you want you exit from a procedure before the procedure would terminate naturally. For example; if the value of a parameter is not suitable, you might want to issue a warning to the user and exit, as example below shows. Procedure DisplayName (s);
Begin
If s = ‘’ Then
Begin
ShowMessage(‘Please enter a name’);
Exit;
End;
ShowMessage(S + ‘ is shown’);
End;
File IO routines DelphiScript has the following IO routines
• Append
• AssignFile
• ChDir
• CloseFIle
• Eof
• Eoln
• Erase
• GetDir
• MkDir
• Read
• Readln
• Reset
• Rewrite
• RmDir
• Write
• Writeln
DelphiScript gives you the ability to write information out to a text file, since DelphiScript is an untyped language, you can only deal with strings. Thus Read/ReadLn routines are equivalent. They read a line up to but not including the next line. A Writeln(String) routine is equivalent to a Write(S) and a Write(LineFeed + CarriageReturn) routine.
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 75
To be able to write out a text file, you need to employ AssignFile, ReWrite, Writeln and CloseFile procedures. To read in a text file, you need to employ the AssignFile, Reset, Readln and CloseFile procedures. This example writes to a text file and adds an end-of-line marker.
Use of Try / Finally / End block is recommended to make scripts secure in the event of an IO failure.
Example Var
InputFile : TextFile;
OutputFile : TextFile;
I : Integer;
Line : String;
Begin
AssignFile(OutputFile,eConvertedFile.Text);
Rewrite(OutputFile);
AssignFile(InputFIle,eOriginalFIle.Text);
Reset(InputFile);
Try
While not EOF(InputFile) do
Begin
Readln(InputFile,Line);
For I := 1 to Length(Line) Do
Line[I] := UpperCase(Line[I]);
Writeln(Outputfile, Line);
End;
Finally
CloseFile(InputFile);
CloseFile(OutputFile);
End;
End;
Delphi Script Reference
76 TR0120 (v1.1) April 26, 2005
Math routines Delphi Script has the following math routines;
• Abs
• ArcTan
• Cos
• Exp
• Frac
• Int
• Random
• Randomize
• Round
• Sin
• Sqr
• Sqrt
• Trunc
String Routines Delphi Script has the following string routines which can manipulate strings of characters. Only a select few routines are shown here.
• Copy
• Format
• Length
• Ord
• Pos
• Pred
• Round
• SetLength
• Succ
• Trunc
• UpCase
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 77
Extension routines The extension routines are used when you are dealing with processes in your scripts especially if you need to extract or set strings for the parameters of processes. Some of the routines are listed below, refer to the DXP RTL and Process references for more details.
Executing parameters of processes in your script, you might need following functions: • AddColorParameter
• AddIntegerParameter
• AddLongIntParameter
• AddSingleParameter
• AddWordParameter
• GetIntegerParameter
• GetStringParameter
• ResetParameters
• RunProcess
Useful functions • SetCursorBusy
• ResetCursor
• CheckActiveServer
• GetActiveServerName
• GetCurrentDocumentFileName
• RunApplication
• SaveCurrentDocument
Useful Dialogs • ConfirmNoYes
• ConfirmNoYesCancel
• ShowError
• ShowInfo
• ShowWarning
Using sets Since Object Pascal’s Set and In keywords are not supported in Delphi Script, to overcome this limitation, you can use these two functions: MkSet and InSet. You should use logical operations to include or exclude elements to set.
MkSet - this is a set constructor. It has variable number of arguments. You can write like Font.Style = MkSet(fsBold,fsItalic).
Delphi Script Reference
78 TR0120 (v1.1) April 26, 2005
InSet - this function is used as substitution of Object Pascal’s In operator. A in B is equal to InSet(A, B). If InSet(A,B) then
ShowMessage(‘A is in B set’)
Else
ShowMessage(‘A not in B set’);
The set operators '+', '-', '*', '<=' and '>=' don't work correctly in Delphi Script. You should use logical operators instead. For example, ASet := BSet + CSet;
should be changed to ASet := BSet or CSet;
in order to achieve the desired result in your script.
Using exception handlers The try keyword introduces a try-except statement or a try-finally statement. These two statements are related but serve different purposes.
Try Finally The statements in the finally block are always executed no matter how control leaves the try block exception, Exit or break. Use try-finally block to free temporary objects and other resources and to perform clean up activities. Typically you do not need more than one try-finally statement in a subroutine.
Example Reset(F);
Try
... // process file F
Finally
CloseFile(F);
End;
Try Except Use try-except to handle exceptional cases for example to catch specific exceptions and do something useful with them, such as log them in an error log or create a friendly dialog box. Since the On keyword is not supported in DelphiScript, so you can use the Raise statement inside the Except block.
Example Try
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 79
X := Y/Z;
Except
Raise(‘A divide by zero error!’);
End;
Raise The Raise keyword is related to the Try keyword. The Raise keyword can be used without parameters to re-raise the last exception. It can also be used with a string parameter to raise an exception using a specific message.
Example Raise(Format('Invalid Value Entered : %d', [Height]));
Note, the On keyword is not supported, thus you cannot use Exception objects as in Borland Delphi.
Delphi Script Reference
TR0120 (v1.0) December 01, 2004 80
Forms and Components In this section:
DelphiScript Components
Designing script forms
Writing Event Handlers.
Introduction to Components The scripting system handles two types of components: Visual and Nonvisual components. The visual components are the ones you use to build the user interface, and the nonvisual components are used for different tasks such as these Timer, OpenDialog and MainMenu components. You use the Timer nonvisual component to activate specific code at scheduled intervals and it is never seen by the user. The Button, Edit and Memo components are visual components for example.
Both types of components appear at design time, but non visual components are not visible at runtime. Basically components from the Tool Palette panel are object orientated and all these components have the three following items:
• Properties
• Events
• Methods
A property is a characteristic of an object that influence either the visible behavior or the operations of this object. For example the Visible property determines whether this object can be seen or not on a script form.
An event is an action or occurrence detected by the script. In a script the programmer writes code for each event handler which is designed to capture a specific event such as a mouse click.
A method is a procedure that is always associated with an object and define the behavior of an object.
All script forms have one or more components. Components usually display information or allow the user to perform an action. For example a Label is used to display static text, an Edit box is used to allow user to input some data, a Button can be used to initiate actions.
Any combination of components can be placed on a form, and while your script is running a user can interact with any component on a form, it is your task, as a programmer, to decide what happens when a user clicks a button or changes a text in an Edit box.
The Scripting system supplies a number of components for you to create complex user interfaces for your scripts. You can find all the components you can place on a form from the Toolbox palette. To place a component on a form, locate its icon on the Tool Palette panel and double-click it. This action places a component on the active form. Visual representation of most components is set with their set of properties. When you first place a component on a form, it is placed in a default position, with default width and height however you can resize or re-position this component. You can also change the size and position later, by using the Object Inspector.
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 81
When you drop a component onto a form, the Scripting system automatically generates code necessary to use the component and updates the script form. You only need to set properties, put code in event handlers and use methods as necessary to get the component on the form working.
Designing script forms A script form is designed to interact with the user within the environment. Designing script forms is the core of visual development. Every component you place on a script form and every property you set is stored in a file describing the form (a DFM file) and has a relationship with the associated script code (the PAS file). Thus for every script form, there is the PAS file and the corresponding DFM file.
When you are working with a script form and its components, you can operate on its properties using the Object Inspector panel. You can select more than one component by shift clicking on the components or by dragging a selection rectangle around the components on this script form. A script form has a title (the Caption property on the Object Inspector panel).
Creating a new script form With a project open, right click on a project in the Projects panel, and a pop up menu appears, click on the Add New to Project item, and choose Script Form item. A new script form appears with the Form1 name as the default name.
Displaying a script form In a script, you will need to have a procedure that displays the form when the script form is executed. Within this procedure, you invoke the ShowModal method for the form. The Visible property of the form needs to be false if the ShowModal method of the script form is to work properly.
ShowModal example Procedure RunDialog;
Begin
DialogForm.ShowModal;
End;
The ShowModal example is a very simple example of displaying the script form when the RunDialog from the script is invoked. Note, you can assign values to the components of the DialogForm object before the DialogForm.ShowModal is invoked.
ModalResult example procedure TForm.OKButtonClick(Sender: TObject);
// Form's Visible property must be false for ShowModal to work properly.
If Form.ShowModal = mrOk Then ShowMessage('mrOk');
If Form.ShowModal = mrCancel Then ShowMessage('mrCancel');
End;
The ModalResult property example here is a bit more complex. The following methods are used for buttons in a script form. The methods cause the dialog to terminate when the user clicks either the OK or Cancel button, returning mrOk or mrCancel from the ShowModal method respectively.
You could also set the ModalResult value to mrOk for the OK button and mrCancel for the Cancel button in their event handlers to accomplish the same thing. When the user clicks either button, the dialog box closes. There is no need to call the Close method, because when you set the ModalResult method, the script engine closes the script form for you automatically. Note, if you wish to set the form's ModalResult to cancel, when user presses the Escape key, simply enable the Cancel property to True for the Cancel button in the Object Inspector panel or insert Sender.Cancel := True in the form's button cancel click event handler.
Accepting input from the user One of the common components that can accept input form the user is the EditBox component. This EditBox component has a field where the user can type in a string of characters. There are other components such as masked edit component which is an edit component with an input mask stored in a string. This controls or filters the input.
The example below illustrates what is happening, when user clicks on the button after typing something in the edit box. That is, if the user did not type anything in the edit component, the event handler responds with a warning message. Procedure TScriptForm.ButtonClick(Sender : TObject);
Begin
If Edit1.Text = '' Then
Begin
ShowMessage('Warning - empty input!');
Exit;
End;
// do something else for the input
End;
Note, A user can move the input focus by using the Tab key or by clicking with the house on another control on the form.
Delphi Script Reference
TR0120 (v1.1) April 26, 2005 83
Responding to events When you press the mouse button on a form or a component, Altium Designer sends a message and the Scripting System responds by receiving an event notification and calling the appropriate event handler method.
See also Writing Scripts
Writing Event Handlers
Using DXP Objects in scripts
Delphi Script Language HelloWorld project from the \Examples\Scripts\DelphiScript Scripts\General\ folder.
ShowModalEg script within the General_Scripts project from the \Examples\Scripts\DelphiScript Scripts\General\ folder.
Writing Event Handlers Each component, beside its properties, has a set of event names. You as the programmer decide how a script will react on user actions in Altium Designer. For instance, when a user clicks a button on a form, Altium Designer sends a message to the script and the script reacts to this new event. If the OnClick event for a button is specified it gets executed.
The code to respond to events is contained in DelphiScript event handlers. All components have a set of events that they can react on. For example, all clickable components have an OnClick event that gets fired if a user clicks a component with a mouse. All such components have an event for getting and loosing the focus, too. However if you do not specify the code for OnEnter and OnExit (OnEnter - the control has focus; OnExit - the control loses focus) the event will be ignored by your script.
Your script may need to respond to events that might occur to a component at run time. An event is a link between an occurrence in Altium Designer such as clicking a button, and a piece of code that responds to that occurrence. The responding code is an event handler. This code modifies property values and calls methods.
List of properties for a component To see a list of properties for a component, select a component and in the Object Inspector, activate the Properties tab.
List of events for a component To see a list of events a component can react on, select a component, and in the Object Inspector activate the Events tab. To create an event handling procedure, decide on what event you want your component to react, and double click the event name. For example, select the Button1 component from the Toolbox panel and drop it on the script form, and double click next to the OnClick event name. The scripting system will bring the Code Editor to the top of the Altium Designer and the skeleton code for the OnClick event will be created.
Delphi Script Reference
84 TR0120 (v1.1) April 26, 2005
For example, a button has a Close method in the CloseClick event handler. When the button is clicked, the button event handler captures the on click event, and the code inside the event handler gets executed. That is, the Close method closes the script form. In a nutshell, you just select a button component, either on the form or by using the Object Inspector panel, select the Events page, and double click on the right side of the OnClick event, a new event handler will appear on the script. OR double click on the button and the scripting system will add a handler for this OnClick event. Other types of components will have completely different default actions.
List of methods for a component To see a list of methods for a component, see the Delphi Script Component Reference.
Using Components in your scripts
Dropping components on a script form To use components from the Tool Palette panel in your scripts, you need to have a script form first before you can drop components on the form. Normally when you drop components on a script form, you do not need to create or destroy these objects, the script form does them for you automatically.
The scripting system automatically generates code necessary to use the component and updates the script form. You then only need to set properties, put code in event handlers and use methods as necessary to get the script form working.
Creating components from a script You can also directly create and destroy components in a script – normally you don’t need to pass in the handle of the form because the script form takes care of it automatically for you, thus you just normally pass a Nil parameter to the Constructor of a component.
For example, you can create and destroy Open and Save Dialogs (TOpenDialog and TSaveDialog classes as part of Borland Delphi Run Time Library).
Delphi Script Reference
TR0120 (v1.0) December 01, 2004 85
Index A
About Example Scripts .............................................7