Vectorworks 2009 VectorScript Language Guide
Vectorworks 2009 VectorScript Language Guide
© 1985‐2008 Nemetschek N.A., Incorporated. All Rights The VectorScript Language Guide was written by
Reserved. Alexandra Duffy, Teresa Heaps, Susan Collins, Jeff Koppi,
and Jeff Geraci at Nemetschek N.A., Incorporated, 7150
Nemetschek N.A., Inc., hereafter referred to as NNA, and
Riverwood Drive, Columbia, MD, 21046, USA. Special
its licensors retain all ownership rights to the MiniCAD®
thanks to Craig Hollinshead.
Vectorworks® computer program and all other computer
programs as well as documentation offered by NNA. Use Illustrations by Alexandra Duffy, Teresa Heaps, and
of NNA software is governed by the license agreement Susan Collins.
accompanying your original media. The source code for
For Defense Agencies: Restricted Rights Legend. Use,
such software is a confidential trade secret of NNA. You
reproduction, or disclosure is subject to restrictions set
may not attempt to decipher, decompile, develop or
forth in subparagraph (c)(1)(ii) of the Rights of Technical
otherwise reverse engineer NNA software. Information
Data and Computer Software clause at 252.227‐7013.
necessary to achieve interoperability with this software
may be furnished upon request. For civilian agencies: Restricted Rights Legend. Use,
VectorScript Language Guide reproduction, or disclosure is subject to restrictions set
forth in subparagraphs (a) through (d) of the commercial
This manual, as well as the software described in it, is Computer Software Restricted Rights clause at 52.227‐19.
furnished under license and may only be used or copied Unpublished rights reserved under the copyright laws of
in accordance with the terms of such license. The the United States. The contractor/manufacturer is
information in this manual is furnished for informational Nemetschek N.A., Incorporated, 7150 Riverwood Drive,
use only, is subject to change without notice, and should Columbia, MD, 21046, USA.
not be construed as a commitment by NNA. NNA
assumes no responsibility or liability for any errors or
Registration and Updates
inaccuracies that may appear in this manual. The Vectorworks Design Series disks are warranted
subject to the conditions of the License Agreement for a
Except as permitted by such license, no part of this
period of six (6) months from the date of purchase by the
publication may be reproduced, stored in a retrieval
end user. A completed Registration Card must be
system, or transmitted, in any form or by any means,
returned to NNA to officially register your copy of
electronic, mechanical, recording, or otherwise, without
Vectorworks.
the express prior written permission of NNA.
Only registered users are entitled to technical support,
Existing artwork or images that you may desire to scan or
the NNA newsletter, maintenance releases, and reduced
copy may be protected under copyright law. The
cost upgrades.
unauthorized incorporation of such artwork into your
work may be a violation of the rights of the author or Defective master disks are replaced free of charge to the
illustrator. Please be sure to obtain any permission end user for six (6) months after purchase. Thereafter,
required from such authors. master disks will be replaced for a nominal service fee set
by NNA.
MiniCAD, Vectorworks, and Renderworks are registered
trademarks of NNA. VectorScript, SmartCursor, and the NNA will make available from time to time upgrades to
Design and Drafting Toolkit are trademarks of NNA. the purchased program for nominal charges. Such
upgrades, along with the original master copy of the
The following are copyrights or trademarks of their
program, shall be considered one program, subject in its
respective companies or organizations:
entirety to the License Agreement.
QuickDraw 3D, QuickTime, Quartz 2D, and Macintosh Vectorworks License Agreement
are registered trademarks of Apple Computer, Inc.
The license agreement binding the use of this software
Microsoft and Windows are registered trademarks of the can be found in the Vectorworks ReleaseNotes directory
Microsoft Corporation in the United States and other or by clicking “License” in the About Vectorworks dialog
countries. box.
All other brand or product names are trademarks or
registered trademarks of their respective companies or
organizations.
Table of Contents
1 Introduction to VectorScript.....................................................................................................................1
Understanding this Guide ........................................................................................................................................1
Some Background On VectorScript .........................................................................................................................1
4 Arrays in VectorScript.............................................................................................................................19
Static Arrays...........................................................................................................................................................19
Dynamic Arrays......................................................................................................................................................20
5 Structures ................................................................................................................................................29
Creating Structures ................................................................................................................................................29
Accessing Values in a Structure ............................................................................................................................30
6 Expressions.............................................................................................................................................33
Simple Expressions ...............................................................................................................................................33
Complex Expressions ............................................................................................................................................33
Operator Precedence.............................................................................................................................................34
Operator Associativity ............................................................................................................................................34
ii | Table of Contents
7 Statements ...............................................................................................................................................41
Assignment Statements .........................................................................................................................................41
Compound Statements ..........................................................................................................................................44
Procedure Statements ...........................................................................................................................................44
GOTO Statements .................................................................................................................................................45
Repetition Statements............................................................................................................................................45
Conditional Statements..........................................................................................................................................48
E Script Encryption..................................................................................................................................137
Encrypting Scripts ................................................................................................................................................137
Include Files and Encryption................................................................................................................................138
Index .........................................................................................................................................................141
iv | Table of Contents
Introduction to VectorScript 1
VectorScript is the scripting language component of the Vectorworks Fundamentals software package. It is a
lightweight programming language which syntactically resembles Pascal, incorporating many of the programming
constructs of that language. VectorScript is actually a “superset” of the Pascal language, extending basic Pascal
capabilities with a number of APIs (application programming interfaces) which provide access to the features and
functionality of the Vectorworks CAD engine.
This guide provides an introduction to using the VectorScript language. The VectorScript Function Reference is a
comprehensive command reference available online. It is located in: VWHelp/VectorScript Reference/
VSFunctionReference.html
This section provides a brief overview of the VectorScript language; it explains what VectorScript can do and what it
canʹt, and provides information on features new to this version of the language.
Document Control
VectorScript provides APIs for controlling the various settings of individual Vectorworks documents. These interfaces
allow you to retrieve and set geometric attributes of the document such as design layer scales or visibility, along with
graphical attributes such as fill or pen color.
Extended Data
VectorScript allows you to manipulate the extended data contained within the document to suit your specific needs.
VectorScript APIs provide access to and control over worksheets, data records, and textures which allow you to
perform ʺdeep editingʺ of your documents.
An Example Script
Letʹs take a look at a simple example to become more familiar with some of the basics of a typical script. The listing
below is an example of a small script which displays a message in the VectorScript message bar, then clears the
message after five seconds:
PROCEDURE FirstExample;
CONST
kGREETING = 'Hello ';
VAR
Some Background On VectorScript | 3
MyMessage : STRING;
BEGIN
myMessage:='VectorScript';
Message(kGREETING,myMessage);
Wait(5);
SysBeep;
ClrMessage;
END;
Run(FirstExample);
The program begins with a statement which names the procedure and identifies it to the VectorScript compiler:
BEGIN
myMessage:='VectorScript';
Message(kGREETING,myMessage);
Wait(5);
SysBeep;
ClrMessage;
END;
Run(FirstExample);
After this statement is what is known as the main program block. The main program block contains areas for declaring
what data storage will be needed by the script when it is run along with an area for the source code of the script, which
provides the instructions on what actions will be performed by the script:
PROCEDURE FirstExample;
CONST
kGREETING = 'Hello ';
VAR Declares data storage for the script
myMessage : STRING;
4 | Chapter 1: Introduction to VectorScript
BEGIN
myMessage:='VectorScript';
Message(kGREETING,myMessage);
Wait(5);
SysBeep; The source code of the script
ClrMessage;
END;
Run(FirstExample);
The script ends with a special statement which tells the VectorScript compiler to execute the script code preceding it:
PROCEDURE FirstExample;
CONST
kGREETING = 'Hello ';
VAR
myMessage : STRING;
BEGIN
myMessage:='VectorScript';
Message(kGREETING,myMessage);
Wait(5);
SysBeep;
ClrMessage;
END;
Run(FirstExample); Tells the VectorScript compiler to run the script
Even though some of the concepts behind the parts of the script may not be clear to you at this point, studying the
example should give you an idea of what a script looks like and how it works. Later sections will explain the various
parts of a script and their underlying concepts in greater detail.
Exploring VectorScript
The best way to really learn any new programming language is to write programs with it. As you read through this
guide and through the online function reference, you are encouraged to try out features as you learn about them.
There are several ways to do this, which make it easy to experiment with VectorScript and learn about the language.
The VectorScript Function Reference guide is available online. It is located in VWHelp/VectorScript Reference/
VSFunctionReference.html
The most basic way to explore VectorScript is to take a Vectorworks document and export it using the Export
VectorScript option. Once you have exported the document, use a text editor to open the document. What you will see
Some Background On VectorScript | 5
is a VectorScript representation of the complete Vectorworks document: objects, layers, classes, document settings, and
so on. You can compare this script code to the source document to see how a particular setting is created using
VectorScript, or you can modify part of the script code and import it into a blank document to see how your changes
affect the document. You can also use parts of this script code in your own scripts, either as‐is or as a basis for your
own custom work.
Another useful technique for exploring VectorScript is to make use of the Custom Tool/Attribute and Custom Selection
commands of Vectorworks. These tool items make use of VectorScript to perform actions in Vectorworks, and you can
use them to explore how to use VectorScript. The Custom Tool/Attribute command lets you save graphical attribute
and tool settings for later use, and Custom Selection lets you define search criteria to select subsets of objects in your
document. Both these techniques can be very useful when writing your own scripts, and you can see how to use these
techniques by opening up the scripts and examining the script code.
Possibly the best technique is to start writing your own scripts from scratch. You can use the Resource Browser in
Vectorworks to create blank document scripts and edit them through the VectorScript Editor. The VectorScript Editor
provides several handy features which give you quick access to API information and other basics of the language.
While exploring VectorScript, you will probably write scripts which don’t execute, or don’t work as you expected. To
correct problems which prevent your script from executing, you can check VectorScriptʹs Error Output file, which will
indicate the source of any fatal errors in your scripts. To correct problems which are preventing your script from
working as desired, you can use the VectorScript debugger to trace through your code and locate the problem. You can
also use the basic technique used by many other languages—insert statements which display the values of relevant
variables in your script. VectorScript provides a convenient tool for this in the Message() statement.
Good luck with VectorScript, and have fun!
6 | Chapter 1: Introduction to VectorScript
Lexical Structures of VectorScript 2
Every programming language has a set of rules which specify how to write programs using that language. These rules
are known as the lexical structure of the language. This structure is the lowest level syntax of a language, specifying
things like how variables are named, what separates one program statement from the next, and so on. This section
explains the basic lexical structure of VectorScript.
Case Sensitivity
VectorScript is not case sensitive. This means that items such as language keywords, variables, function names, and
any other identifiers can be specified using uppercase, lowercase, or a mixed case and still be compatible with other
variations of the same item. This differs from languages such as JavaScript or C.
Symbols
In VectorScript, symbols are the atomic, or smallest meaningful, elements of the language. VectorScript source code is
comprised of a succession of these symbols, which form the instructions in the script that tell Vectorworks what
actions to perform. Another term for symbols is tokens. Several rules govern how symbols are defined:
Each symbol is written as a series of ASCII characters, and symbols must conform to the following rules:
• Each symbol must be unbroken; symbols cannot occur inside of other symbols.
• Symbols must be comprised of 8‐bit ASCII characters (or, more technically, the ISO‐8859‐1 character set).
• Symbols can have a wide variety of meanings and uses in VectorScript. They can, among other uses, represent
data storage locations, indicate mathematical operations to be performed, or control script execution.
• Symbols are separated by other characters known as delimiters. Delimiters separate symbols and identify them
as discrete items; symbols and delimiters must alternate.
Delimiters
Delimiters allow the VectorScript compiler to distinguish variables, statements, and other language items as separate,
meaningful objects within the script. The principal delimiters in VectorScript are spaces, tabs, and the newline
character. VectorScript uses these characters to separate language objects, but otherwise ignores them. Delimiters
cannot be inserted within a symbol; a delimiter placed within a symbol will break it into two separate items (and will
generate a syntax error).
Certain lexical constructs in VectorScript can also function as delimiters while performing other functions within the
script code. For example, the VectorScript compiler can process the mathematical expression
circumference:=2*3.14159*radius
because the * character and the term := both act as delimiters in addition to the other operations they perform. These
terms, known as special symbols, are one type of lexical construct which perform this ʺdouble dutyʺ in VectorScript.
Others include comments and compiler directives; later sections will cover these items in greater detail.
Since spaces, tabs, and new lines do not have meaning to the VectorScript compiler, you are free to use them to indent
and format your script code. This type of formatting makes your scripts easy to read and understand.
8 | Chapter 2: Lexical Structures of VectorScript
Comments
Comments in VectorScript are used to place descriptive text within script code. They are most often used to document
script code for your reference and for others who may work on your scripts. The VectorScript compiler ignores
comments.
The general syntax for VectorScript comments is:
(* block comment
{Some comment line.}
{Another comment.}
*)
Literals
Literals in VectorScript are data values that appear directly within the script code. Literals can be numbers, text
strings, the Boolean values TRUE and FALSE, or the special value NIL. The following subsections describe each literal
type.
Integer Literals
Integer values in VectorScript are represented as a sequence of digits with an optional minus sign prepending the
sequence (for negative values).
3 ‐255 1000000
Floating-point Literals
Floating‐point values may be represented using either the traditional decimal point notation or by using exponential
(scientific) notation.
A floating‐point value in decimal format is represented as:
• An optional plus or minus sign, followed by
• The integral part of the value, followed by
• A decimal point and the fractional part of the number.
Identifiers | 9
A floating‐point value in exponential notation is represented as:
• An optional plus or minus sign, followed by
• The integral part of the value, followed by
• A decimal point and the fractional part of the number, followed by
• The letter e or E, followed by
• An optional plus or minus sign, followed by
• A one, two, or three digit integral exponent value. The preceding integral and fractional parts of the value are
multiplied by the exponent.
VectorScript also allows you to use dimensional notation with numeric literals and values, and will recognize common
dimensional symbols for units such as feet, inches, or meters. See “Units and Numeric Values in Scripts” on page 121
for details on how to use numeric literals with dimensional notation.
String Literals
Strings literals are any sequence of zero or more characters enclosed within single quotes. They are represented using
the following rules:
• Each literal must be enclosed in single quotes.
• Constants may be written on multiple lines, but return characters will be converted to spaces.
• Blanks, tabs, and carriage returns count as valid characters within literals.
• The maximum length of a string literal is 255 characters.
• A string literal with nothing between the quotes is assumed to be the null string.
• To write a single quote within a string literal, use two consecutive single quotes in the literal statement.
Boolean Literals
Boolean literals in VectorScript represent a “truth value” (whether something is true or false). Most comparison
operations in VectorScript yield a Boolean value that indicates whether the operation succeeded or failed. Since there
are two possible truth states, there are two Boolean literals in VectorScript: the keywords TRUE and FALSE.
Identifiers
Identifiers in VectorScript are symbols which are used to refer to something else: constants, variables, data types,
procedure or function names, and other similar items.
The rules for writing VectorScript identifiers are similar to most programming languages:
10 | Chapter 2: Lexical Structures of VectorScript
• The first character must be a letter or an underscore.
• Subsequent characters may be a character, digit, or underscore.
• Identifiers may not contain spaces, tabs, or other characters.
• Identifiers may be any length, but the first 255 characters are significant (i.e., recognized by the VectorScript
compiler).
Identifiers which do not follow the specified rules will prevent a script from compiling, and will generate a
VectorScript compiler error.
Value Identifiers
Invalid Identifiers
Reserved Words
Reserved words are a special class of symbol in VectorScript. Reserved words are specialized symbols which have
significant meaning to the VectorScript compiler—they allow the compiler to determine important information about
your script and how to use that information to compile and execute your script correctly. You should avoid using
reserved words as identifiers in your scripts, as they will cause errors and/or unexpected behavior.
VectorScript Keywords
The following table lists the reserved words (also known as keywords) in VectorScript:
The following table lists reserved words which have no current meaning to the VectorScript compiler, but have been
reserved for possible use in the future. You should also avoid using them in your scripts, as they may cause problems
with future versions of the language.
Special Symbols | 11
Other Keywords
The following table lists reserved words which have no current meaning to the VectorScript compiler, but have been
reserved for possible use in the future. You should also avoid using them in your scripts, as they may cause problems
with future versions of the language.
Since VectorScript is not case sensitive, corresponding upper and lower case versions of terms (begin and BEGIN, for
example) are equivalent and should be avoided.
Special Symbols
Special symbols are another specialized class of symbol in VectorScript. Special symbols, like reserved words, have
significant meaning to the VectorScript compiler. They indicate actions the compiler should take and how to control
and execute your script, as well as functioning as delimiters in other script statements.
+ ‐ *
/ ^ =
( ) [
] { }
. , $
<> <= >=
:= .. **
The table lists characters and character pairs recognized as special symbols in the VectorScript language. The specific
meanings and uses of the individual special symbols will be covered in detail in later sections.
12 | Chapter 2: Lexical Structures of VectorScript
Variables, Constants, and Data Types 3
The previous section introduced the concept of literals, data values embedded directly within your VectorScript code.
Scripts that operate only on such static data are rather limited and inflexible; to move beyond this limitation,
VectorScript uses constants and variables. Constants and variables are names (more technically, identifiers) that
which have associated data values; we say that the variable or constant “stores” or “contains” the value.
Constants and variables provide a way to store and manipulate values by name. In the case of constants, the value
cannot be changed during script execution; in the case of variables, however, the value associated with a name may be
changed at any point by assigning a new value to the name (hence the term “variable”).
Another important VectorScript concept is that of data types. As the name implies, data types are the kinds of data
that can be manipulated by your scripts. Data types provide structure and meaning to the information being
manipulated by a script, allowing VectorScript to process it efficiently and safely.
This section explains how to use variables and constants in your scripts, and provides detailed information on the
various data types available in VectorScript.
Variables
Variables are created through a variable declaration. The variable declaration associates the variable name identifier
with a specific data type. This data type tells the VectorScript compiler how much memory storage will need to be
allocated for the data that will be stored in that location.
The general syntax for a variable declaration is:
<identifier>(,<identifier>,...) : <data type>;
Multiple identifiers of a single data type can be specified by a comma delimited list.
For simple data and array types, these declarations occur in one location in the script, known as the VAR block. This
area of the script is located at the beginning of the main program block, prior to the main body of script code, and is
indicated by the VAR keyword. The VAR block is the only location where variables can be declared; unlike languages
such as Basic or JavaScript, variables cannot be declared in the source code of the script.
VectorScript uses the information provided by the VAR block to allocate memory needed for the script to execute
properly. In the example below, two variables are declared to provide data storage for the script:
PROCEDURE Example_1;
VAR
s:STRING;
i:INTEGER;
BEGIN
s:='VectorScript';
i:=2;
14 | Chapter 3: Variables, Constants, and Data Types
Message('Hello ',s);
Wait(i);
ClrMessage;
END;
Run(Example_1);
Note that values are not actually assigned to the variables declared in the VAR block. The actual assignment of values
into the variable storage locations occurs in the body of the script. The purpose of the VAR block is to define storage
requirements, not to define data.
Constants
Constants are created using a constant definition. Constant definitions also associate an identifier with a storage
location in memory, but unlike variable declarations, a value is immediately assigned to the location. The value of the
constant cannot be modified by a script after it is defined.
The general syntax for a constant definition is:
<identifier> = <value>;
Constants, unlike variables, do not require an explicit data type.
Constant definitions also occur at one location in the script, the CONST block. This area of the script is located at the
beginning of the main program block, prior to both the main body of script code and the VAR block. The block is
indicated by using the CONST keyword. Like the VAR block, the CONST block is the only location where this type of
storage declaration (constant definitions) is allowed.
In the following example, constants are used to define values that could be used to customize the script for a specific
target, such as a particular market:
PROCEDURE Example_1;
CONST
{capitalized to distinguish them from variables}
LOCAL_GREETING_ENGLISH = 'Hello ';
LOCAL_GREETING_FRENCH = 'Bonjour ';
VAR
s:STRING;
i:INTEGER;
BEGIN
s:='VectorScript';
i:=2;
Message(LOCAL_GREETING_ENGLISH,s);
Wait(i);
ClrMessage;
VectorScript Data Types | 15
END;
Run(Example_1);
Once the value is defined, it can be used in the script as needed. Note again that no data type is required for constants;
VectorScript will implicitly convert the value to the proper type if needed.
Constants can store any basic data type (INTEGER, LONGINT, REAL, STRING, CHAR, or BOOLEAN). VectorScript also
supports the use of trigonometric, ordinal, and other mathematical functions in defining constants. The following
table lists functions which are supported in the constant definition block and can be used to define constants in scripts.
INTEGER
Values of type INTEGER are a subset of the whole numbers. INTEGER values may be in a range of -32767 to 32767,
and may not contain any fractional or decimal parts. Numbers which contain fractional or decimal parts will be
truncated if assigned to a variable of type INTEGER.
In VectorScript, variables of type INTEGER will only accept INTEGER values or LONGINT values which fall within the
valid INTEGER range.
LONGINT
Values of type LONGINT are also a subset of the whole numbers. LONGINT values can represent a larger range of
values than the INTEGER type, with the range for LONGINT values spanning from -2,147,183,647 to
2,147,183,647.
LONGINT values, like INTEGER values, may not contain any fractional or decimal parts. Numbers which contain
fractional or decimal parts will be truncated if assigned to a variable of type LONGINT. In VectorScript, variables of
type LONGINT will accept either LONGINT or INTEGER values.
Arithmetic operations involving values of types INTEGER and LONGINT follow these rules:
16 | Chapter 3: Variables, Constants, and Data Types
• All integer constants in the valid value range of type INTEGER are considered to be of type INTEGER. All integer
constants in the range of type LONGINT, but not in the range of type INTEGER, are considered to be of type
LONGINT.
• When both operands of an operator (or the single operand of a unary operator) are of type INTEGER, the result is
of type INTEGER (truncated if it falls outside the range of values which can be represented by that type).
Similarly, if both operands are of type LONGINT, the result is of type LONGINT.
• When one operand is of type LONGINT and the other is of type INTEGER, the INTEGER operand is converted to
LONGINT and the result is of type LONGINT. If this value is assigned to a variable of type INTEGER, it is
truncated.
REAL
Values of type REAL (also known as floating‐point values) are a subset of the real numbers, and can store fractional or
decimal parts of a number. Valid REAL values fall within a range of 1.9 x 10e-4951 to 1.1 x 10e4932.
In VectorScript, variables of type REAL will accept REAL, LONGINT, or INTEGER values. LONGINT and INTEGER
values will be converted to the REAL data type before being assigned to a variable.
STRING
STRING values are used to store and manipulate textual data within scripts. A variable of type STRING will store up to
255 characters of textual data, and STRING data values will support any valid ASCII character. Data values of type
STRING are also compatible with string and character literals.
CHAR
CHAR data values store a single ASCII character, and they are a distinct type from the STRING data type. CHAR values
can be used to obtain and convert single characters from STRING values, and they are often used to define special
characters for use in a script.
STRING and CHAR values are compatible types, and values of these types may be assigned and compared directly.
BOOLEAN
BOOLEAN data values may hold one of two values, the truth values (and reserved words) TRUE or FALSE. Values of the
BOOLEAN type are more closely similar to Java or JavaScript boolean values in that they are a distinct type; unlike C or
C++, they do not use numeric values to simulate TRUE or FALSE.
Boolean values are generally the result of comparison operations that occur within a script, and they are most often
used for decision making during script execution.
VectorScript Data Types | 17
HANDLE
HANDLE values in VectorScript are used to store a reference to other Vectorworks data in memory. Values of type
HANDLE are most often used to reference data related to objects, layers, classes, or other Vectorworks internal
structures. VectorScript makes extensive use of HANDLE values throughout the VectorScript API as an easy means of
retrieving or setting this data directly from a script.
Aside from a reference to data located in memory, HANDLE values can also be set to the value NIL. As explained in
“The NIL Literal” on page 9, the value NIL indicates no reference exists or was found.
Since HANDLE values are references to dynamic memory locations, they should not be stored or otherwise treated as if
they were permanent reference to a given item within a document. Storing and reusing HANDLE values can cause
errors or other unpredictable behavior within your scripts.
VECTOR
VectorScript provides the specialized VECTOR data type to support vector operations within VectorScript. Vectors are
used to represent quantities which have an associated displacement, characterized by a direction and a distance (or
magnitude). A VectorScript VECTOR consists of three component REAL values which can also be treated as a single
unit value.
When used in conjunction with the vector API of the VectorScript language, VECTOR values can be highly useful in
performing complex geometric computations in scripts. Details on this API may be found in the VectorScript Function
Reference.
POINT
The POINT data type is used to store the coordinates of a 2D point. It is a compound data type consisting of two
component REAL values: x and y. The value is assumed to be in the units of the current document, and relative to the
document origin.
POINT3D
The POINT3D data type is used to store the coordinates of a point in 3D space. It is a compound data type consisting of
three component REAL values: x, y, and z. The value is assumed to be in the units of the current document, and relative
to document origin.
RGBCOLOR
The RGBCOLOR data type can store a color as three components: red, green, and blue. Each component is a LONGINT
value.
18 | Chapter 3: Variables, Constants, and Data Types
Arrays in VectorScript 4
An array in VectorScript is a collection of data values referenced by a single identifier. Arrays allow large amounts of
data to be stored and manipulated during script execution.
The data values contained within an array are stored in a contiguous set of memory locations, and can be accessed
either randomly or in sequential order. In VectorScript, you can access this data by means of an array index. An array
index is an INTEGER value corresponding to a specific storage location within the array. VectorScript arrays are
indexed (that is, an individual data value is retrieved from the array) by enclosing the index value in square brackets
after the array name. For example, if my_data is an array, and i is an INTEGER variable, then
my_data[i]
is an element of the array.
VectorScript provides support for two types of arrays: static arrays (ARRAY), and dynamic arrays (DYNARRAY). This
section explains the syntax and conventions for using arrays in your scripts.
Static Arrays
Static arrays (ARRAY) are declared using the same method as used for variables, except that a series of storage locations
is allocated for the array values, rather than a single location typical of a variable. Static array declarations occur in the
VAR block along with other variables.
Static arrays come in one‐ and two‐dimensional varieties. The general syntax for one‐dimensional static arrays is:
<identifier> : ARRAY [ m..n ] OF <data type>;
In the array declaration, the term [m..n] indicates the dimension, or size, of the array. An array declared with a
dimension of [1..10] will allocate ten contiguous storage locations in memory. Static arrays support any valid
fundamental data type, as well as the user‐defined STRUCTURE type (see “Creating Structures” on page 29 for details).
To retrieve a value from an element of a one‐dimensional array, the same bracket notation described earlier is used.
The array name should appear to the left of the brackets, and a non‐negative INTEGER value representing the array
index should appear within the brackets:
j := values[3];
values[23] := 15.5;
total := price[i] + tax;
An array index may be any constant non‐negative INTEGER value or expression which resolves to such a value.
The following example illustrates the practical use of a one‐dimensional array:
PROCEDURE Example_41;
VAR
s:STRING;
i:INTEGER;
words:ARRAY[1..10] OF STRING;
BEGIN
20 | Chapter 4: Arrays in VectorScript
words[1]:='VectorScript ';
words[2]:='is ';
words[3]:='a ';
words[4]:='fine ';
words[5]:='language.';
FOR i:=1 TO 5 DO s:=Concat(s,words[i]);
Message(s);
END;
Run(Example_41);
In the example, a ten element array of STRING is declared, and the script code begins with assignment of values to the
elements of the array. In the assignments, constants are used to represent the array indices, but a variable or other
identifier which evaluates to an INTEGER value could have been used in their place. Such an identifier is used later in
the Concat() function call to reference array elements.
Two‐dimensional static arrays extend the syntax of a one‐dimensional array by adding an additional array index to the
declaration:
j := values[3,5];
values[23,1] := 15.5;
total := price[i,j] + tax;
If we think of the two‐dimensional array in terms of rows and columns, we would use two index values to indicate the
row and column position of the array element to be indexed.
Dynamic Arrays
Dynamic arrays (DYNARRAY) in VectorScript are similar to static arrays, with the notable exception of how they are
dimensioned, or sized. While static arrays are explicitly sized when they are declared in the VAR block of your script,
the size of a dynamic array is declared during the actual execution of a script. Dynamic arrays can also be resized at
any point during script execution to suit your data storage requirements. As with static arrays, dynamic arrays
support any valid fundamental data type, as well as the user‐defined STRUCTURE type (see “Creating Structures” on
page 29 for details).
Dynamic arrays can also be specified as one‐ or two‐dimensional. The general syntax for a one‐dimensional dynamic
array is:
ALLOCATE int_values[1..5];
The range specified inside the brackets indicates the number of elements to be created and reserved for storage.
The following example illustrates practical use of a dynamic array within a script:
PROCEDURE Example_42;
VAR
i,j,numtxt : INTEGER;
h : HANDLE;
textStore: DYNARRAY[] OF STRING;
BEGIN
numtxt:=Count(((T=Text) & (SEL=TRUE)));
j:=1;
ALLOCATE textStore[1..numtxt];
h:=FSActLayer;
h:=NextSObj(h);
END;
ALLOCATE textStore[1..numtxt+2];
22 | Chapter 4: Arrays in VectorScript
TextOrigin(2,2);
CreateText('New text 1');
numtxt:=numtxt+1;
textStore[numtxt]:=GetText(LNewObj);
TextOrigin(2,4);
CreateText('New text 2');
numtxt:=numtxt+1;
textStore[numtxt]:=GetText(LNewObj);
FOR i:=1 TO numtxt DO BEGIN
Message('Array element ',i,' contains ', textStore[i]);
Wait(1);
END;
END;
Run(Example_42);
In the example, a dynamic array is used to store the text of any selected strings that may be found in the selection set.
The script begins by declaring the dynamic array, textStore, along with several other variables. In the VAR block
declaration, the dynamic array is specified, but no space is allocated at this point for storage.
The body of the script begins with storing the number of selected text objects found within the selection set in the
variable numtxt. This value is then used with the ALLOCATE keyword:
ALLOCATE textStore[1..numtxt];
to initialize the amount of storage space in the dynamic array.
Next, the script processes the selected items, and when it encounters a text object, stores the text in an element of the
array. Since the text objects within the selection set were counted, textStore is sized to provide sufficient storage
within the array for the exact number of text strings that were found.
Once all the objects have been processed, the array can be redimensioned to allocate more or less space as needed. In
the example, additional storage space is reserved with another call to ALLOCATE,
ALLOCATE textStore[1..numtxt+2];
and use the newly added storage locations to store the text created by the script. The script concludes by displaying
the values currently stored within the textStore array.
Note that the existing data values stored in the array are preserved when the array is re‐dimensioned. If an array is
redimensioned to a larger size during execution of the script, VectorScript will preserve all the values currently in the
array. VectorScript will also attempt to preserve as many data values as possible if an array is redimensioned to a
smaller size. In the case of dimensioning to a smaller size, any values contained in locations beyond the newly defined
boundaries of the array will be lost.
Dynamic Arrays | 23
vec_field[5][2];
will access the second field (the y‐component) of the vector in element 5 of the one‐dimensional array vec_field.
Two‐dimensional arrays can also use this notation; if vec_field2 is a two‐dimensional array, then
vec_field2[4,5][2];
will access the second field of the vector located in the fourth row and fifth column of the array.
To access a vector field using dot notation, simply append the dot (field access) operator and field identifier to the
array reference you want to index. Using the previous example,
vec_field[5].y;
will perform the same operation, accessing the second field (the y‐component) of the vector in element 5 of
vec_field. Two dimensional arrays work in a similar fashion; the reference
vec_field2[4,5].y;
will access the y‐component of the vector located in the fourth row and fifth column of vec_field2.
Assigning values from a STRING variable or constant to a static CHAR array works in a similar fashion. If the CHAR
array has a length less than the length of the STRING value to be assigned, the value will be truncated to fit the array.
For instance:
PROCEDURE Example_43;
VAR
Part_name: STRING;
NameArray: ARRAY[1..16] OF CHAR;
BEGIN
part_name:= 'Acme Left-handed Smoke Shifter';
NameArray:=part_name;
END;
Run(Example_43);
In the example, the STRING value assigned to the variable part_name would be truncated to
Acme Left-handed
when assigned to the array. When using static CHAR arrays to handle STRING values, be sure to declare the size of the
array to accommodate the longest STRING value expected to be stored within the array.
In contrast to static CHAR arrays, dynamic CHAR arrays will automatically size to the length of the STRING value being
assigned to the array. For example:
PROCEDURE Example_44;
VAR
sampleString: STRING;
mytext: DYNARRAY[] OF CHAR;
BEGIN
sampleString:= 'VectorScript now handles lots of text';
mytext:= sampleString;
END;
Run(Example_44);
If the array mytext was declared but not previously used, the assignment would size the array length to 36, and the
array would contain the string
PROCEDURE Example_45;
VAR
h : HANDLE;
theText : STRING;
textArray : DYNARRAY[] OF CHAR;
BEGIN
h:=FSActLayer;
theText:= GetText(h);
CreateText(theText);
END;
Run(Example_45);
In the example, you would be limited to returning the first 255 characters of the text string. By using a dynamic array:
PROCEDURE Example_45;
VAR
h : HANDLE;
theText : STRING;
textArray : DYNARRAY[] OF CHAR;
BEGIN
h:=FSActLayer;
textArray:= GetText(h);
CreateText(textArray);
END;
Run(Example_45);
You can retrieve the entire text string and store it in the dynamic array. The entire text string can then be used in other
operations.
To set or retrieve the record field string, use the name of the CHAR array (without brackets) in place of the STRING
parameter or variable. For example:
PROCEDURE Example_46;
VAR
theText : STRING;
longtext : ARRAY[1..512] OF CHAR;
BEGIN
theText:= GetRField(FSActLayer,'Boring Info','Boring Notes');
CreateText(theText);
END;
Run(Example_46);
In the example, using a STRING variable would be limited to retrieving only the first 255 characters of the text string
stored within the field. By using a CHAR array:
PROCEDURE Example_46;
VAR
theText : STRING;
longtext : ARRAY[1..512] OF CHAR;
BEGIN
longtext:= GetRField(FSActLayer,'Boring Info','Boring Notes');
CreateText(textArray);
END;
Run(Example_46);
In the example, up to 512 characters of text from the field can be retrieved and stored in the array. Alternately, the
dynamic array could be sized to support whatever amount of text might be found in the record field (up to 32K of
text).
PROCEDURE Example_47;
VAR
s : STRING;
Dynamic Arrays | 27
In the example, a CHAR array is used in place of a STRING as the source value for the Copy() function. The result of
the Copy() operation is then assigned to a STRING variable. String API function calls support both static and
dynamic CHAR arrays.
The following VectorScript API functions have CHAR array support.
Creating Structures
Structures are declared in a special section of your scripts, the TYPE block. This optional section, which is located
between the CONST and VAR sections of the main program block, is the only location where structures may be
declared. There is no limit to the number of structures that may be declared in a TYPE block.
The general syntax for a structure declaration is:
The declaration begins with the identifier used to refer to the structure. Following this identifier is the special
symbol = and the keyword STRUCTURE, which indicates that the member declarations which follow should be
grouped under the specified identifier name. The members of a structure are declared just as you would declare any
other variable, with all the same rules for declaring variables applying to the member declarations. The structure
declaration is terminated by using the END keyword.
Structure declarations, unlike variables or constants, do not reserve storage space for data. Instead, they define a new
data type which can be used in your scripts as you would any of the fundamental data types. Such a user‐defined type
can be used to declare variables or arrays in the same manner as using INTEGER, STRING, or other fundamental types.
For example, suppose you wish to define a structure which represents a 2D point. The structure which represents the
point can be defined as shown below:
Point = STRUCTURE
x,y : REAL;
END;
The structure POINT contains two members of type REAL, but no space is allocated until variables or arrays are
declared using the structure as a user‐defined type:
30 | Chapter 5: Structures
PROCEDURE StructExample1;
TYPE
POINT = STRUCTURE
x,y : REAL;
END;
VAR
centerPt, target : POINT;
vertex_list : ARRAY[1..20] OF POINT;
BEGIN
END;
Run(StructExample1);
The centerPt and target variables each contain storage for the two REAL values contained within the structure,
and the vertex_list array reserves sufficient memory to store twenty POINT items, or forty REAL values. The POINT
structure acts as a “template” to use when defining data value storage for your script.
centerPt.x:= 0;
total:= windowData.cost + tax;
This notation can also be used when comparing values or when passing values to VectorScript or user‐defined
functions:
partData.location:= GetLName(ActLayer);
GetObject(partData.name);
Arrays of structures also support the use of dot notation to reference individual structure members:
vertices[5].x:= 2.67;
vertices[6].y:= vertices[5].y + 2.6;
The reference to a member of a structure in an array element is created by appending the member operator and the
member name to an array element reference.
Accessing Values in a Structure | 31
As mentioned before, structures support the use of static arrays as data members. Arrays within structures present a
bit more of a syntactical challenge when referencing a member value, but otherwise they are not difficult to use. To
reference a value in an array element within a structure, append the member operator and a member array element
reference to the structure instance identifier:
p.name[5]:= 'Marvin';
total:= total + winAssembly1.cost[k];
As with non‐member arrays, any expression or constant which resolves to an INTEGER value can be used when
indexing the member array element.
It is also possible to have arrays of structures which have arrays as members. Once again, a combination of the
member operator with a reference to the desired array element is used to obtain the data value. In this case, array
element references will appear on both sides of the member operator. This can lead to some rather interesting looking
syntax within a script:
doorAssembly[3].cost[4]:= 24.55;
subtotal:=subtotal+doorAssembly[i].cost[j]+doorAssembly[i].cost[j+1];
These expressions are perfectly valid; however, they do require extra attention to ensure the correct syntax is specified.
Structures containing other structures as members also present an additional layer of complexity when referencing
members of the nested structure. The key in this situation is to use member chaining to descend through the data
hierarchy to the desired value. For example:
PROCEDURE Example_51;
TYPE
POINT = STRUCTURE
x,y : REAL;
END;
CIRCLE = STRUCTURE
ctr : POINT;
radius : REAL;
END;
VAR
c1,c2 : CIRCLE;
BEGIN
c1.ctr.x:= 4.5;
c2.ctr.y:= c1.ctr.y;
END;
Run(Example_51);
32 | Chapter 5: Structures
The CIRCLE structure declaration makes use of an instance of the POINT structure to more logically organize data. To
reference either the x- or y‐component of the POINT instance, chain the members of the nested structures:
c1.ctr.x:= 4.5;
c2.ctr.y:= c1.ctr.y;
References to the member ctr and its members x and y are chained together using the member operator to reference
and access the values in the nested structure. Chaining of members in nested structures can be used repeatedly in
scripts to access structure members which may be nested several levels deep.
Expressions 6
Every value in VectorScript is designated by way of an expression. An expression is a “phrase” in VectorScript that can
be evaluated to produce a value. Expressions can be simple, consisting of a single component expressing the value, or
complex, expressing the value through a combination of other expressions and operations on them.
Simple Expressions
Simple expressions use a single component, or operand, to express a value. Simple expressions in VectorScript are
most often constants (such as string or numeric literals), variable names, or function names.
The value of a simple constant expression is essentially the constant itself. The value of a simple variable expression is
the value that is associated with the variable identifier. The value of a function expression is the value returned when
the function has completed execution.
Complex Expressions
Complex expressions, also known as compound expressions, derive their values from combining or transforming the
values of other expressions. For example, the value of expression
i + 1.7;
is derived from the combining values of 1.7 and i. Since we know that both 1.7 and i are also simple expressions
which each have their own value, they can be combined to obtain a value.
In the expression above, the resulting value is determined by adding the values of the two simpler expressions. The
expression uses an operator, in this case the plus sign, to perform an operation (addition) on the simpler expressions
and to combine them into a more complex expression.
The expressions combined by the plus sign in the example above can also be referred to as operands. Operators are
usually grouped by the number of operands that they require in order to perform their intended operations.
VectorScript supports two types of operators, unary operators, which require a single operand, and binary operators,
which require two operands.
Each operator produces a resulting value whose data type is determined both by the operator and the operands from
which the value was derived. Operators may have restrictions on the types of operands with which they are
compatible, and all these factors impact the data type of the resulting value.
34 | Chapter 6: Expressions
Operator Precedence
Just as it does in mathematics, operator precedence in VectorScript controls the order in which operations are
performed. Operators having a higher precedence have their operations performed before those having a lower
precedence. In the expression
p = q + r * s;
the multiplication operator ( * ) has higher precedence than the addition operator, so the multiplication operation is
performed before the addition. The assignment operator ( = ) has the lowest precedence of all the operators, so the
association, or assignment, of the value to the variable p occurs only after the other operations are completed.
Operator precedence can be overridden by the explicit use of parentheses. To force the addition operation to be
performed first in the prior example, parentheses would be used to modify the expression to be:
p = (q + r) * s;
In everyday use, it is good practice to use parentheses if you are unsure about precedence in order to make the
evaluation order explicit.
Operator Associativity
Operator associativity specifies the order in which operations of the same precedence are performed. Left‐to‐right
associativity means that operations are performed left to right when operators are of equal precedence. For example,
the expression
p = q + r + s;
is equivalent to the expression
p = ((q + r) + s);
because the addition operator has left‐to‐right associativity. Conversely, the expression
w = x = y = z;
is equivalent to the expression
w = ( x = (y = z));
because the assignment operator has right‐to‐left associativity.
Arithmetic Operators
Arithmetic operators perform such familiar mathematical operations as addition or multiplication on the specified
operands. Arithmetic operators are restricted to working on numeric VectorScript data types. The table below
summarizes the arithmetic operators available in VectorScript.
Unary negation ( - )
When - is used as a unary operator preceding a single operand, it performs a negation operation on the operand. That
is, it converts a positive value to an equivalently negative value, or it converts a negative value to its equivalently
positive value.
Addition ( + )
The + operator adds two numeric operands. This operator is limited to addition only; unlike in many other languages,
this operator may NOT be used to concatenate strings.
Subtraction ( - )
The - operator subtracts the second operand from the first. Both operands must be numeric.
Multiplication ( * )
The * operator multiplies its two numeric operands.
Division ( / )
The / operator divides the first operand by its second operand. The operator performs floating‐point division, always
returning a value of type REAL even when both operands are of INTEGER or LONGINT type.
j:= 36 DIV 5;
will return a result of 7, which is assigned to the variable j.
k:= 36 MOD 5;
will return a value of 1, which is assigned to k.
36 | Chapter 6: Expressions
Exponentiation ( ^ )
The ^ operator raises the first operand to the power indicated by the second operand; that is, x^y is equivalent to x to
the yth power.
Comparison Operators
Comparison operators in VectorScript are used to compare values of various types and return a Boolean value (true or
false) result. The results of expressions using comparison operators are most often used to control the flow of script
execution.
The table below summarizes the comparison operators available in VectorScript.
Equality ( = )
The = operator returns TRUE if its two operands are exactly equal, and returns FALSE if they are not equal. The
operands may be of any type. For operands of type STRING, the values are compared on a character‐by‐character
basis, and must contain exactly the same characters.
Inequality ( <> )
The <> operator tests for the exact opposite of the = operator. If two equal values are compared using the inequality
operator, the resulting value will be FALSE. Comparison of two values which are not equal will yield a TRUE result.
Logical Operators
Logical operators perform the rough equivalent of a comparison operation on Boolean values. Logical operators use
Boolean algebra to evaluate their operands and return the result of the operation. In programming, they are most often
used to express complex comparisons which involve multiple operands by linking smaller expressions together.
The following table summarizes the comparison operators available in VectorScript.
Logical OR ( OR )
The OR operator evaluates to TRUE if the first operand or the second operand are TRUE. Both operands must evaluate
to FALSE for the result returned to be FALSE. Expressions using the OR operator will always evaluate both operands
before returning the result of the expression, regardless of the value of the first operand.
Logical Short-circuit OR ( | )
The OR operator evaluates to TRUE if the first operand or the second operand are TRUE. Both operands must evaluate
to FALSE for the result returned to be FALSE. Expressions using the | operator will not evaluate the second operand if
the first operand returns a value of TRUE. If the second operand should have any side effects (such as those produced
by a function call returning value) they may not occur. In general, it is best to avoid expressions such as the following
which combine side effects with the | operator:
Other Operators
Assignment Operator ( := )
As described in “Variables” on page 13, variables are associated with (assigned) a value. This value can also be
modified at any point during execution of your scripts. Both these operations are performed using the assignment
operator.
The := operator expects the first (left‐hand) operand to be a variable, array, element, or vector field/structure member.
The second (right‐hand) operand can be an arbitrary value of any type, though the value must be compatible with the
data type of the first operand. The value of the expression is the value of the right‐hand operand.
The assignment operator has right‐to‐left associativity, which means that the second operand is evaluated first in the
expression (and is how VectorScript determines if the value and the variable are of compatible types).
price[3]
will evaluate to the value in the third element of the price array. For a two dimensional array plant_data, the
expression
plant_data[2,i+4]
will evaluate to the value contained in the element specified by [2,i+4]. The expression i+4 must evaluate to an
INTEGER value in order to be used as an operand in the expression.
Other Operators | 39
distance_vector1.x
will evaluate to the value in the x field of the vector distance_vector1. When dealing with a structure, the
expression
window_data.cost
will evaluate to the value within the member cost of the structure instance
window_data.
40 | Chapter 6: Expressions
Statements 7
Statements in VectorScript are the actions of the language. Whereas expressions in VectorScript can be thought of as
“phrases” that can be evaluated to a value, expressions don’t “do” anything. To make something happen, you need to
use a VectorScript statement, which is akin to a complete sentence or a command. Statements in VectorScript perform
the execution tasks of your script, managing your script data and controlling the flow of script execution.
Statements in VectorScript are always found in “blocks,” and a script is simply a large block containing a collection of
statements. Each statement in VectorScript is terminated with a semi‐colon, which indicates to the VectorScript
compiler where each statement ends.
This section describes the various statement types found in VectorScript and explains their syntax in detail.
Assignment Statements
Assignment statements set the value of a variable or like identifier in a script. Assignment statements use the
assignment operator (:=) to set the value of the identifier on the left‐hand side of the symbol to the value of the
constant or identifier on the right‐hand side of the symbol. This may also be thought of as assigning the value of the
identifier on the right‐hand side to the identifier on the left.
The generalized syntax for assignment statements is:
PROCEDURE Example_71;
CONST
kInitialValue = 0;
TYPE
POINT = STRUCTURE
x,y:REAL;
END;
VAR
s : STRING;
i : INTEGER;
h : HANDLE;
textdata : ARRAY[1..100] OF STRING;
p1,p2 : POINT;
BEGIN
{ assignment of constant value to a variable }
i:= kInitialValue;
{ assignment of return value to variable }
42 | Chapter 7: Statements
h:= FSObject(ActLayer);
{ assignment of return value to variable }
s:= GetText(h);
{ assignment of variable value to array element }
textdata[1]:= s;
{ assignment of values to structure members }
p1.x:= 0; p1.y:= 2;
{ assignment of member value to another member }
p2.x:= p1.y;
{ assignment of member value to another member }
p1.y:= p2.x;
END;
Run(Example_71);
From the example, it is evident that the assignment statement is very flexible. The example makes use of constants,
variables, structure fields, and function return values when assigning values to an identifier. Note also that more than
one statement can reside on a single line, as long as they are separated by a semi‐colon indicating the end of each
statement.
While assignment statements are very flexible in how they get or assign values, they do observe some rules regarding
compatibility of data types. When writing assignment statements, the following rules should be observed:
• A variable of REAL type may be set to a REAL, INTEGER, or LONGINT value, as well as any expression yielding
those results.
• A LONGINT variable may be set to a LONGINT or INTEGER value or any expression yielding such a value. It may
also be set to a REAL value, but the value will be truncated and rounded to the nearest whole value.
• An INTEGER variable may be set to an INTEGER value, or any expression yielding such a value. It may also be set
to a REAL value, but the value will be truncated and rounded to the nearest whole value.
• A BOOLEAN variable may be set a BOOLEAN value or an expression yielding such a value.
• A STRING variable may be set to a STRING or CHAR value or any expression yielding those values. It may also be
set to an ARRAY or DYNARRAY OF CHAR value; however, the value in the array will be truncated to 255
characters.
• A CHAR variable may be set to a CHAR value or any expression yielding a CHAR value. It may also be set to a
STRING value, but will be truncated if the STRING is greater than 1 character in length.
• A HANDLE variable may be set to a HANDLE value or any expression yielding a HANDLE value.
Assignment statements also support block copying of values in arrays when they are used without an array element
index in a script. This method facilitates transferring large amounts of data without the need for copying on an
element‐by‐element basis. For example:
PROCEDURE Example_72;
VAR
values1,values2:ARRAY[1..5] OF INTEGER;
Assignment Statements | 43
BEGIN
values1[1]:= 2;
values1[2]:= 4;
values1[3]:= 8;
values1[4]:= 16;
values1[5]:= 32;
END;
Run(Example_72);
In order to transfer the values in values1 to values2, it would appear that multiple assignment statements are
needed, one for each array element. For large arrays, this would be a time‐consuming task. Fortunately, VectorScript
overloads (extends the functionality of) the assignment operator so that operation to copy the values becomes a single
statement:
PROCEDURE Example_72;
VAR
values1,values2:ARRAY[1..5] OF INTEGER;
BEGIN
values1[1]:= 2;
values1[2]:= 4;
values1[3]:= 8;
values1[4]:= 16;
values1[5]:= 32;
values2:= values1;
END;
Run(Example_72);
The assignment statement copies the data from the values1 array directly into the corresponding elements of the
values2 array. This sort of assignment operation can be also be performed with dynamic arrays; in both cases,
however, the dimensions of the arrays on both sides of the assignment operator must be exactly the same in order to
complete the operation.
Vectors and structures may also be copied in this manner; the member values of the item on the right side of the
assignment operator will be copied into the corresponding member fields of the item on the left side of the operator.
For example, the values in a vector direction_vector1 could be copied into another vector:
new_vector:= direction_vector1;
The values in the fields of direction_vector1 would be copied into the fields of new_vector without the need for
assignment statements for each field.
44 | Chapter 7: Statements
Compound Statements
VectorScript provides compound statements as a way to execute several statements as if they were a single statement.
This capability is quite useful when it is necessary to combine statements and execute them together—for instance,
when being executed as a branch of a control statement or in a loop.
To create a compound statement from a sequence of statements, preface the first statement in the sequence with the
BEGIN keyword. The sequence is terminated with the END keyword, and each statement in the sequence is separated
by a semi‐colon. For example:
BEGIN
i:=1;
j:= (3*2)+5;
Message(i+j);
END;
The three statements contained within the BEGIN and END keywords will be executed together when the compound
statement is called.
The generalized syntax for compound statements is:
BEGIN
<statement>; [<statement>; <statement>;...]
END;
Compound statements may also be nested; the VectorScript compiler will associate the last BEGIN keyword with the
next END keyword in the script, the second‐last BEGIN with the following END, and so on. Mismatched BEGIN-END
pairs will cause a VectorScript error to occur.
If you noticed that the body of a script looks suspiciously similar to a compound statement, you would be correct; the
script body of any VectorScript script, user‐defined procedure, or user‐defined function is in fact a single compound
statement.
Procedure Statements
Procedure statements in VectorScript call predefined VectorScript API function calls as well as user‐defined
procedures and functions to perform actions within a script. With VectorScript API function calls, the actions are
performed directly by Vectorworks; user‐defined function calls encapsulate other VectorScript source code; which is
executed when the procedure statement is called in a script.
The general syntax for procedure statements is:
Message('Hello VectorScript');
or
SetSelect(h);
GOTO Statements | 45
are examples of procedure statements in VectorScript. For more details on user‐defined procedures and functions, see
“User‐Defined Procedures” on page 55 and “User‐Defined Functions” on page 57.
GOTO Statements
GOTO statements transfer execution of the script to the beginning of the statement following the label associated with
the GOTO. For example:
PROCEDURE Example_73;
LABEL 100;
VAR
i,j : INTEGER;
BEGIN
i:= 10;
j:= 2;
IF (j MOD 2 = 0) THEN GOTO 100;
i:= i * 5;
100: i:= i + 1;
Message(i);
END;
Run(Example_73);
Repetition Statements
VectorScript supports three methods of executing a section of a script repeatedly—the process referred to as looping.
The repetition statements supported by VectorScript are the FOR statement, the WHILE statement, and the REPEAT
statement.
46 | Chapter 7: Statements
The initial and final values, or limit values, of the control variable are set in the FOR statement. These values may be
INTEGER, LONGINT, or CHAR values, and can be either constants or values derived from an expression. The value of
the control variable is modified and evaluated by the FOR statement prior to each pass through the script section
controlled by the statement.
FOR statements come in two varieties: the FOR-TO statement, and the FOR-DOWNTO statement. In the FOR-TO
statement, the value of the control variable is incremented (increased) by one on each pass through the section
controlled by the statement. For example:
j:= 9;
FOR i:=10 DOWNTO 1 DO BEGIN
Message('Pass ',i-j,'(',i,') through FOR loop.');
j:= j - 2;
END;
In the FOR statement, the value of i is decremented on each pass until it reaches the limit value of one. Also note that a
compound statement can be used to execute any number of other statements within the FOR statement structure.
The following cautions should be observed when working with FOR statements:
• Do not try to change the value of the control variable from within the FOR statement; doing so can lead to
unpredictable results.
• Do not include the control variable in either of the limit expressions of the FOR statement.
• If the limit values are equal, the FOR statement will execute its controlled statement exactly once.
• If the limit values are reversed, the FOR statement will be skipped.
PROCEDURE Example_74;
VAR
h:HANDLE;
BEGIN
h:= FActLayer;
WHILE (h <> NIL) DO BEGIN
SetSelect(h);
h:=NextObj(h);
END;
END;
Run(Example_74);
In the example, a handle to the first object on the active layer is returned by the FActLayer() function call. If there
are no objects on the active layer, the calls to select the object and obtain the next object on the layer are bypassed.
If there were objects on the layer, the example would automatically exit the loop when it ran out of objects to process.
This is because the NextObj() call returns NIL when it cannot return a handle, and since the WHILE statement will
evaluate the expression before executing its controlled statement, the example would bypass the controlled statement
once the expression evaluated to FALSE (h = NIL). Unlike a FOR statement, the WHILE statement allows execution to
be controlled from within the controlled statement.
PROCEDURE Example_75;
VAR
h:HANDLE;
BEGIN
h:= FActLayer;
REPEAT
SetSelect(h);
48 | Chapter 7: Statements
h:=NextObj(h);
UNTIL (h = NIL);
END;
Run(Example_75);
In this format, the statements within the REPEAT-UNTIL structure would be executed at least once, whether or not h
was initially NIL, which could cause detrimental effects or errors. Generally speaking, REPEAT statements should be
used in conditions where executing the controlled statement will not have a negative impact. WHILE statements are
most useful when the condition controlling their execution may have already been satisfied; REPEAT statements, on
the other hand, are most useful when the condition can be satisfied only by executing the statement.
Also note that REPEAT statements do not require the use of BEGIN or END, as the REPEAT and UNTIL keywords create
their own compound statement out of the statements between them.
Conditional Statements
VectorScript supports two methods of making decisions within a script which affect the flow of execution—a process
referred to as branching. The conditional statements supported by VectorScript are the IF statement and the CASE
statement.
The IF Statement
The VectorScript IF statement evaluates a BOOLEAN control expression and executes a controlled statement only if the
expression evaluates to TRUE. IF statements can also be optionally written to execute a second statement if the control
expression evaluates to FALSE.
The general syntax for IF statements is:
PROCEDURE Example_76;
VAR
Conditional Statements | 49
i:INTEGER;
BEGIN
i:= Ord('c');
IF (i > 48) THEN IF (i > 57) THEN IF (i > 65) THEN IF (i > 90) THEN
IF (i > 97) THEN IF(i < 123) THEN Message('Lower case alpha')
ELSE Message('Out of range') ELSE Message('Some punctuation')
ELSE Message('Upper case alpha') ELSE Message('Some punctuation')
ELSE Message('Number') ELSE Message('Out of range');
END;
Run(Example_76);
If the matching of IF and THEN becomes confusing, you can clarify the source code by using compound statements or
by applying indentation and comments:
PROCEDURE Example_76;
VAR
i:INTEGER;
BEGIN
i:= Ord('c');
{out of range}
IF (i > 48) THEN
{number}
IF (i > 57) THEN
{punctuation}
IF (i > 65) THEN
{upper alpha}
IF (i > 90) THEN
{punctuation}
IF (i > 97) THEN
{lower alpha}
IF(i < 123) THEN
Message('Lower case alpha')
ELSE
Message('Out of range')
ELSE
Message('Some punctuation')
ELSE
Message('Upper case alpha')
50 | Chapter 7: Statements
ELSE
Message('Some punctuation')
ELSE
Message('Number')
ELSE
Message('Out of range');
END;
Run(Example_76);
The control expression may evaluate to an INTEGER, CHAR, or BOOLEAN value. For example:
PROCEDURE Example_77;
VAR
j:INTEGER;
BEGIN
j:= Ord('C');
CASE j OF
49: Message('Number');
77: Message('Upper case alpha');
110: Message('Lower case alpha');
OTHERWISE Message('Out of range');
END;
Conditional Statements | 51
END;
Run(Example_77);
The variable j evaluates to an INTEGER value, and this value is compared to the list of constants in the CASE
statement. In the example, the value of j falls outside of the listed constants, so the OTHERWISE clause is executed.
CASE statements provide some flexibility when specifying constants. For instance, there may be applications of the
CASE statement where several cases will need to execute the same code. Rather than use redundant options, the CASE
statement lets you specify a comma delimited list of constants for a single CASE option:
PROCEDURE Example_78;
VAR
j:INTEGER;
BEGIN
j:= Ord('C');
CASE j OF
49: Message('Number');
58,59,60,61,62,63,64: Message('Non alpha printable character');
110: Message('Lower case alpha');
OTHERWISE Message('Out of range');
END;
END;
Run(Example_78);
Should the control expression evaluate to any of the values in the list, the associated statement will be executed.
For longer contiguous lists of constant values, the CASE statement also supports the use of ranges within the CASE
statement constant specification. These ranges specify a contiguous list of constant values to be associated with a
statement to be executed:
PROCEDURE Example_78;
VAR
j:INTEGER;
BEGIN
j:= Ord('C');
CASE j OF
48..57: Message('Number');
58,59,60,61,62,63,64: Message('Non alpha printable character');
65..90: Message('Upper case alpha');
97..122: Message('Lower case alpha');
OTHERWISE Message('Out of range');
52 | Chapter 7: Statements
END;
END;
Run(Example_78);
Ranges and comma delimited lists may be mixed for further flexibility in associating constants with an executable
statement:
PROCEDURE Example_78;
VAR
j:INTEGER;
BEGIN
j:= Ord('C');
CASE j OF
48..57: Message('Number');
33..47,58..64,91..96:Message('Non alpha printable character');
65..90: Message('Upper case alpha');
97..122: Message('Lower case alpha');
128,133,134,168..170: Message('Special characters');
OTHERWISE Message('Out of range');
END;
END;
Run(Example_78);
In the example, it can be seen that the available methods of specifying CASE statement constants provide the ability to
specify complex options for branching in a very concise format. Ranges and lists also work with the other supported
constant types:
PROCEDURE Example_78;
VAR
j:CHAR;
BEGIN
j:= 'C';
CASE j OF
'0'..'9': Message('Number');
'A'..'Z': Message('Upper case alpha');
'a'..'z': Message('Lower case alpha');
OTHERWISE Message('Out of range');
END;
Conditional Statements | 53
END;
Run(Example_78);
Like other statements, CASE statements can also support the use of compound statements as the controlled statement
to be executed. Extending this concept, it is also possible to create nested CASE statements to handle even more
complex branching in scripts:
PROCEDURE Example_78;
VAR
j:CHAR;
BEGIN
j:= 'C';
CASE j OF
'0'..'9': Message('Number');
'A'..'Z': Message('Upper case alpha');
'a'..'z': Message('Lower case alpha');
OTHERWISE BEGIN
CASE Ord(j) OF
33..47,58..64,91..96:Message('Non alpha printables');
128..159:Message('Accented characters');
168..170: Message('Special characters');
OTHERWISE Message('Out of range');
END;
END;
END;
END;
Run(Example_78);
Some cautions to be observed when using CASE statements:
• Constant values in the CASE statement must have the same type as the value of the controlling expression.
• Constant types may not be mixed in a single CASE statement.
54 | Chapter 7: Statements
User Defined Functions 8
In addition to the over 700 function calls built into the API, VectorScript also lets you create your own user‐defined
functions. By creating these custom functions, you can break large script tasks into smaller ones, and build on the
work that you have done previously instead of starting over from scratch. Another term for user‐defined functions is
subroutines which, as the name implies, are pieces of script code which perform tasks within the main script.
User‐defined functions come in two varieties: procedures, which perform actions but are not associated with a value,
and functions, which perform actions and also have an associated value that can be used in situations requiring a
constant or expression‐derived value.
This section describes in detail how to create and use your own procedures and functions, and addresses some of the
issues involved in using them within scripts.
User-Defined Procedures
User‐defined procedure subroutines are the most common type of subroutine. They allow commonly used code to be
“encapsulated” under a single identifier which can easily be called from within a script.
User‐defined procedures are declared after the definition (CONST, TYPE, and VAR) blocks of a script, but before the
script body. To create a user‐defined procedure to use within a script, you will need to create a procedure declaration
statement which associates an identifier with the subroutine and defines how the subroutine is to be used. The general
syntax for user‐defined procedures is:
PROCEDURE SubrExample2;
VAR
n,sum:INTEGER;
BEGIN
n:=IntDialog('Enter the limit value','0');
{sum of squares for the first n integers}
sum:= n*(n+1)*(2*n+1)/6;
Message('The sum of squares is: ',sum);
END;
Run(SubrExample2);
56 | Chapter 8: User Defined Functions
and modify it so that the sum of squares code can be easily reused whenever it is needed. To do this, a subroutine is
needed to contain the code which performs the operation. Creating the subroutine begins by writing a procedure
declaration statement and the skeleton of the subroutine:
PROCEDURE SubrExample2;
VAR
n,sum:INTEGER;
PROCEDURE SumOfSquares(limit:INTEGER;VAR result:INTEGER);
BEGIN
END;
BEGIN
n:=IntDialog('Enter the limit value','0');
{sum of squares for the first n integers}
sum:= n*(n+1)*(2*n+1)/6;
Message('The sum of squares is: ',sum);
END;
Run(SubrExample2);
The declaration statement associates the identifier SumOfSquares with the new subroutine. Following the subroutine
identifier is the parameter list for the subroutine. This optional list defines a method of moving data in and out of the
subroutine. While it is possible to refer to values in the enclosing program blocks directly, doing so would eliminate
the ability to easily use the subroutine in other code, which is one of the major advantages of using subroutines.
The parameter list declares a set of identifiers (and their associated data types) that will be used to pass data to and
from the subroutine; the VAR keyword indicates an identifier that will be used to pass data out of the subroutine to the
calling code. Identifiers in the parameter list can be treated as variables and used within the subroutine script code.
When the subroutine is called in the script, the parameter list as shown in the declaration is replaced with a list of
variable identifiers that provide and/or receive the data being passed through the parameters. The order and types of
the variable identifiers must exactly match those in the declaration.
Now that the skeleton of the subroutine is in place, the summation script code can be moved into the subroutine and
modified to work with the subroutine:
PROCEDURE SubrExample2;
VAR
n,sum:INTEGER;
PROCEDURE SumOfSquares(limit:INTEGER;VAR result:INTEGER);
BEGIN
result:= limit*(limit+1)*(2*limit+1)/6;
END;
BEGIN
User-Defined Functions | 57
The final change needed to the script is to modify the main body of the script to use the subroutine:
PROCEDURE SubrExample2;
VAR
n,sum:INTEGER;
PROCEDURE SumOfSquares(limit:INTEGER;VAR result:INTEGER);
BEGIN
result:= limit*(limit+1)*(2*limit+1)/6;
END;
BEGIN
n:=IntDialog('Enter the limit value','0');
{sum of squares for the first n integers}
SumOfSquares(n,sum);
Message('The sum of squares is: ',sum);
END;
Run(SubrExample2);
Note again that when the script is called in the main program block, the SumOfSquares parameter list is replaced by
the variables n and sum. The value contained in n is passed into the subroutine, where it is referred to through the
identifier limit. The resulting value is stored in the local identifier result, and is passed back to the main program
block and stored in the variable sum when the subroutine completes its execution.
By using a subroutine, the script can be broken up into manageable chunks which are easy to understand and to
debug. The SumOfSquares subroutine can also be reused as many times as needed in the current script, and the
subroutine can be copied and used in other scripts.
User-Defined Functions
User‐defined functions incorporate all the features of user‐defined procedures, but they have one additional feature
which makes them extremely useful when writing scripts: an associated value. User‐defined functions, unlike
procedures, can pass data out of the subroutine through a return value, which associates the value with the subroutine
identifier. This means that, like a variable, a function can be used wherever a value is required—in an expression, an
assignment statement, or other operation in a script.
User‐defined functions, like procedures, are declared between the definition blocks and the body of the script. To
create a user‐defined function, a function declaration statement will be used to associate an identifier with the
subroutine and define how it will be used. The general syntax for user‐defined functions is:
58 | Chapter 8: User Defined Functions
PROCEDURE SubrExample2;
VAR
n,sum:INTEGER;
PROCEDURE SumOfSquares(limit:INTEGER;VAR result:INTEGER);
BEGIN
result:= limit*(limit+1)*(2*limit+1)/6;
END;
BEGIN
n:=IntDialog('Enter the limit value','0');
{sum of squares for the first n integers}
SumOfSquares(n,sum);
Message('The sum of squares is: ',sum);
END;
Run(SubrExample2);
The SumOfSquares subroutine provides a handy reusable piece of code which is very useful, but the result is
returned to the main script in such a way that it is difficult for anyone reading the script code to determine how the
value is obtained. In this instance, the return value mechanism of a function subroutine can be used to provide a much
more user‐friendly method. To create the function subroutine, the first step is to make some changes to the declaration
statement:
PROCEDURE SubrExample2;
VAR
n,sum:INTEGER;
FUNCTION SumOfSquares(limit:INTEGER):INTEGER;
BEGIN
result:= limit*(limit+1)*(2*limit+1)/6;
END;
User-Defined Functions | 59
BEGIN
n:=IntDialog('Enter the limit value','0');
{sum of squares for the first n integers}
SumOfSquares(n,sum);
Message('The sum of squares is: ',sum);
END;
Run(SubrExample2);
The first change to the declaration is to convert the keyword from PROCEDURE to FUNCTION to indicate the correct
type of subroutine. The output parameter result is then eliminated, since a return value will be used for the
subroutine’s output. Next, a return value data type is added to the declaration.
Once the declaration statement has been modified, one additional change to the subroutine is needed to associate the
result value with the subroutine identifier. VectorScript performs this association by using an assignment statement,
except that the identifier used on the left side of the statement is the subroutine identifier:
PROCEDURE SubrExample2;
VAR
n,sum:INTEGER;
FUNCTION SumOfSquares(limit:INTEGER):INTEGER;
BEGIN
SumOfSquares:= limit*(limit+1)*(2*limit+1)/6;
END;
BEGIN
n:=IntDialog('Enter the limit value','0');
{sum of squares for the first n integers}
SumOfSquares(n,sum);
Message('The sum of squares is: ',sum);
END;
All that is left to do now is to modify the main script to match the new syntax of the function:
PROCEDURE SubrExample2;
VAR
n,sum:INTEGER;
FUNCTION SumOfSquares(limit:INTEGER):INTEGER;
BEGIN
SumOfSquares:= limit*(limit+1)*(2*limit+1)/6;
END;
BEGIN
60 | Chapter 8: User Defined Functions
As you can see, using a function subroutine in this instance makes for much more readable code, and simplifies the
interface of the subroutine as well. In general, functions are best suited to subroutines which return a value that is the
result of a calculation or other similar operation. Procedures should be used when creating a subroutine that performs
an operation which does not return a value.
Parameters
User‐defined subroutines, like the built‐in functions of the VectorScript API, make use of parameters and parameter
lists to move data values in and out of subroutines.
SumOfSquares(n,sum);
the value contained in the variable n would be assigned to the value parameter limit for use within the subroutine.
Program Blocks and Block Scope | 61
Variable parameters in VectorScript are the opposite of value parameters—they are used to pass data values out of a
subroutine. They are denoted by the VAR keyword which precedes them in the parameter list, and like value
parameters, act as local variables within the subroutine. In the SumOfSquares example:
SumOfSquares(n,sum);
the value contained in the variable parameter result would be assigned to the variable sum when the subroutine
finished execution.
PROCEDURE Main;
Subroutine “A”()
Subroutine “B” ()
BEGIN
END;
BEGIN
END;
Subroutine “C”()
BEGIN
END;
BEGIN
END;
In the example, the scope of an identifier is determined by its location:
62 | Chapter 8: User Defined Functions
An identifier is considered undefined outside the program block where it was declared and may not be accessed or
referred to in script code outside of the block. If the block in which the identifier is declared is a subroutine, this means
that the identifier will be undefined in any block enclosing the subroutine. Any attempt to refer to or evaluate the item
from source code in the blocks enclosing the subroutine will cause an error and will cause the script to fail.
The following example also illustrates the concept of block scope:
PROCEDURE WoodPrice;
CONST
kTax:=0.05;
VAR
boardFeet,price,totalCost:REAL;
PROCEDURE CalcCost(feet,ppf:REAL; VAR cost:REAL);
VAR
baseCost:REAL;
FUNCTION AddTax(rawcost:REAL):REAL;
BEGIN
AddTax:= rawcost+(rawcost*kTax);
END;
{ begin CalcCost code }
BEGIN
baseCost:= feet*ppf;
cost:= AddTax(baseCost);
END;
{ end CalcCost code }
{ begin main script }
BEGIN
boardFeet:= RealDialog('Enter no. of feet','0');
price:= RealDialog('Enter price per foot','0');
CalcCost(boardFeet,price,totalCost);
Message('Total cost is $',totalCost:6:2);
END;
Program Blocks and Block Scope | 63
In the example there are three program blocks, or areas of scope. The largest block is the main script, WoodPrice;
contained within it is the subroutine block CalcCost, and within CalcCost is the subroutine function and program
block AddTax.
Any variable or constant identifiers defined in the WoodPrice block can be referred to in the WoodPrice script code,
and can also be referenced from within any of the subroutines declared within the block. These items are said to have
global scope because they are defined at the top level of the script, and can be accessed from any subroutine within the
script.
Identifiers defined in the CalcCost subroutine (including those in the declaration statement) can be referred to in the
CalcCost subroutine, or within the AddTax function. They are undefined, however, in the WoodPrice block, which
lies outside the CalcCost scope. This means that items such as baseCost or the subroutine AddTax cannot be
referenced directly from the main body of the WoodPrice script.
The identifiers defined in the AddTax subroutine have the smallest scope of any of the blocks in the script; they are
available only to code contained within that subroutine. They are undefined for and cannot be referenced from the
CalcCost and WoodPrice program blocks. In the example, the kTax constant can be referenced directly in the
AddTax function because kTax is defined in the main script and has global scope. The result of AddTax, however,
cannot be accessed directly from the main script, since it is declared within the CalcCost subroutine and is only valid
within that subroutine.
64 | Chapter 8: User Defined Functions
User Interface 9
Vectorworks provides several ways for a script to present a user interface to display or gather information from the
user. These include Help Tags, Tool Tips, Messages, Predefined Alerts, and Custom Dialog boxes. This section briefly
introduces these features, and then describes Custom Dialog boxes in detail.
The simplest user interface feature that VectorScript plug‐ins should support is Help Tags or Tool Tips. This feature
simply identifies the plug‐in by name (and an additional short description) when the user hovers the cursor over a tool
icon or a menu item. Plug‐ins are discussed in detail in “Using VectorScript Plug‐ins” on page 83.
The “VectorScript Message” palette is another simple user interface feature. A script can call the “Message()”
function to display one line of information to the user. The function takes multiple arguments, and will concatenate
the pieces together. This feature can be used for status or progress information. Since it is a palette, not an alert, it does
not interrupt the user’s workflow.
Predefined Alerts
To notify the user of an error condition, provide a warning, or ask for confirmation, a script can use one of the several
predefined alerts. With one function call the script can easily present a modal alert dialog box which requires the
user’s attention before he or she can continue. For example:
Controls
Every custom dialog box is comprised of dialog box controls, items which accept user input of one kind or another.
Dialog box controls are designed using easily understood metaphors which allow the user to quickly comprehend
how a dialog box control operates. Once the user understands these simple concepts, it becomes easy for the user to
quickly enter data and define complex combinations of settings for a given task. Controls are also designed to provide
interactive feedback for the user which guides and informs them as they interact with the dialog box.
Controls are organized within the dialog box by means of a dialog box layout, which positions and orients the
controls for display. The dialog box layout provides a logical structure for the controls, allowing the user to quickly
process information contained in the dialog box as well as facilitating data entry into the dialog box.
VectorScript provides a rich set of predefined controls for use in custom dialog boxes. Along with definition functions
for each control, VectorScript provides functions for defining and managing the dialog box layout, as well as functions
for managing control‐related data and for creating associated help for each control.
Events
From the script side, the interaction between the user and the dialog box is viewed as a series of events. Each action the
user initiates (such as a keystroke or a mouse click) is viewed as a discrete event which is passed to and processed by
the script. The actions taken by the script in response to an event vary from script to script, and are defined according
to what the script is designed to accomplish. This flexibility in handling of events is what makes it possible to apply a
relatively small set of dialog box features to a wide range of script applications.
Processing of user events in VectorScript is accomplished through the use of a structured subroutine known as the
event handler function. The event handler function contains all the code needed to manage the operation of the dialog
box while it is displayed.
Check Box
Check box controls display a standard check box option control.
Check box control
Custom Dialog Box Controls | 67
Check boxes are traditionally used to display options that can be set independently of other option items in a dialog
box.
Color Popup
Allows the user to select a color from the Color Palette set.
Color Palette
Color palette controls display a system color palette when clicked. The selected color value is returned for use in the
script.
The value returned by the color palette control is a decimal representation of a hexadecimal color value. This value
must be converted to corresponding RGB values for use with VectorScript color functions.
Edit Integer
Edit integer controls are a specialized type of edit control designed for handling numeric input. Edit integer controls
return values directly as an INTEGER value, eliminating the need for string‐number conversions.
Edit integer controls also support in‐line expressions which result in a numeric value.
Edit Real
Edit real controls are a specialized type of edit control designed for handling numeric input. Values from edit real
controls are returned directly as a REAL value, eliminating the need for string‐to‐number conversions.
Edit real controls
Edit real controls can be configured to display the field value in one of several formats, such as dimensions or angular
values. Edit real controls also support in‐line expressions which result in a numeric value.
Edit Text
Edit text controls display a single‐line editable field in which the user can enter or modify text.
The text value contained in the control can be retrieved using functions provided by the API. Text contained within an
the control can also be updated during run‐time. Text in edit text controls is always left‐justified.
Custom Dialog Box Controls | 69
Gradient Slider
The gradient slider can be used to indirectly manipulate gradient resources.
Group Box
Group boxes are used to associate related items in a dialog box. Other controls, such as radio buttons, pulldown
menus, and even other group boxes, can be embedded within a group box control.
Group box title
Group box control
Checkbox title control
The size of the control is determined by the size of the controls which are embedded in the group box. The title of a
group box is optional; group boxes defined without titles will display with a complete box border. Group boxes do not
return a data value.
Group box titles can consist of a control (checkbox or radio button) or static text. The title control automatically enables
or disables all other controls contained within the group box.
Group box borders can also be configured as invisible to group items as a layout unit within the dialog box.
Group boxes and the controls contained within them can be treated as a single control when performing dialog layout.
Adjustments to the group box control will automatically adjust any controls contained within the group box.
Image
Image controls display an image or texture.
Image Pane
Image pane controls display an image retrieved from a VectorScript resource file:
Image pane controls are sized to the dimensions of the graphic image being displayed. The graphic displayed in the
image pane control can be updated during script run‐time by setting the active image resource for the control.
Image Popup
Image popup controls allow the user to display a selectable preview list of resources.
Custom Dialog Box Controls | 71
List Box
List box controls display a menu containing one or more selection options in a list box format. The user may select an
option from the available list items as the active control option.
The user‐selected option is highlighted in the list box view. List box options can be navigated by highlighting or
tabbing into the control and using the arrow keys to move up and down the list of items available in the control.
VectorScript API functions for retrieving and managing pulldown menu control options also work with list box
controls.
As of Vectorworks 10, list boxes can have multiple columns, each with its own column width. By default, list boxes are
created with one column. To add a column, use the VectorScript function AddListBoxTabStop, which takes a tab
stop as a parameter. Each tab stop is given as a character position. Hence, each succeeding tab stop must be at a greater
character position than the previous one.
Once all tab stops have been set up, data can then be added to the list box (all tab stops must be set before data can be
added). Data is added in the usual way, using calls to InsertChoice. To align text at a tab stop, tab characters are
inserted in the string passed to InsertChoice. The string for an entire line must be passed to InsertChoice all at
once; it is not possible to pass just a part of a line.
List Browser
List browser controls can display a collection of items; each item can display one or more columns of associated
information. Information in items can be displayed as text, an icon, or both. Each column can also display text
information above the items in column headers. The item information can either be static (not changed by the user), or
edited by an in‐place editing control. Currently, the available editing controls are the multi‐item radio edit control and
the multi‐state edit control.
To create a new list browser control, call the function CreateLB, specifying the desired width and height. By default,
there is one column of data. To add more columns, call InsertLBColumn in the SetupDialogC case of the dialog
handler routine. To add rows of data to the list browser, call InsertLBItem for each row. There are many more
functions to customize the list browser; see the VectorScript Function Reference for details.
74 | Chapter 9: User Interface
Marker Popup
Allows the user to select a line marker style.
Pattern Popup
Allows the user to select a fill pattern from the pattern palette.
Pulldown Menu
Pulldown menu controls display one or more selection options in a menu format. The user may select one item from
the available options as the active control option.
Pulldown menu control
(closed state)
When in its closed state, the active menu option is displayed in the control. When the control is selected, all menu
options are displayed, with the active option highlighted:
Pulldown menu control
(open state)
Custom Dialog Box Controls | 75
Pulldown menu options can also be navigated by highlighting or tabbing into the control and using the arrow keys to
move up and down the list of options.
VectorScript provides API functions for retrieving and managing pulldown menu control options.
Push Button
Push button controls display a standard dialog box button. The control is automatically sized based on the specified
text string.
Button text can be updated at runtime using the SetControlText function.
Radio Button
Radio button controls display a standard radio button option control.
Radio buttons are traditionally used in pairs or groups of three to display a set of related options where only one of the
settings is active at any time. Related radio button controls are referred to as a radio button group.
Separators
A line can be added to a dialog box group box to separate the items. Enter 0 as the separator’s length to automatically
size the line length to that of a group (if the line is part of a group) or dialog box (if the line is not part of a group).
76 | Chapter 9: User Interface
Pulldown Separator
A pulldown separator adds a line to a pulldown menu to separate the items in the menu list.
Slider
Slider controls allow the user to select from a range of allowable values by positioning the control’s slider bar indicator.
Slider controls are displayed with a fixed width, and are only displayed in a horizontal orientation.
Slider controls display range increments as tick marks located under the slider bar. The range increment is a fraction of
the maximum value specified for the slider; the number of marks displayed can vary from 1 to 10, depending on the
specified value.
Static Text
Static text controls display a non‐modifiable text string in the dialog box. They are used as labels for other controls, or
to display informational text.
Custom Dialog Box Controls | 77
Static text strings are left‐justified by default; limited right‐justification can be obtained by using alignment functions
provided by the API. Static text controls support updating of the control text during script run‐time.
Standard Icon
Several VectorScript routines exist for presenting simple alert dialog boxes (see “Predefined Alerts” on page 65).
However, with the Standard Icon control, it is possible to present a more complex dialog box, and still give it the
appearance of an alert.
To create a standard icon in a dialog box, call the function CreateStandardIconControl and specify one of the
icon numbers. The icon should be positioned at the top left corner of the dialog box.
1 Informational icon
2 Stop
3 Warning
4 Question mark
Swap Control
A swap control manages multiple overlapping groups of controls. Only one group is visible at a time. In this way, it is
very similar to a Tab Control, except that the Swap Control does not provide tab buttons for the user to click. The
swapping is done programmatically, and can be hooked up to any other control or event.
For example, a dialog box may contain a scrolling list of items on the left, and a swap control on the right. As the user
selects items in the list, the swap control can respond by changing the active pane on the right. This can be used for a
settings type of dialog box, or when there are too many choices to use a Tab control effectively. Another example
would be a dialog box with a set of radio buttons to control which swap pane is visible.
78 | Chapter 9: User Interface
To create a new swap control, call the function CreateSwapControl. Then, for each possible swap pane, create a
group control, place other controls inside the groups, and call the function CreateSwapPane. In the event handling
routine for the dialog box, call the function DisplaySwapPane in response to the appropriate user actions.
Tab Pane
The tab pane control creates a dialog box that uses tab panes. A tab “button” is visible for each pane, with one pane
visible at a time. The tab control can also be part of a dialog box.
Tab pane control
procedure CreateDialog;
VAR
id: LONGINT;
result : LONGINT;
BEGIN
id := CreateLayout(’Revise Layer Link’, TRUE, ’Update’,
’Cancel’);
result := RunLayoutDialog(id,NIL);
END;
RUN(CreateDialog);
This is the basic dialog box container in which the rest of the dialog box definition will be created.
CreateLayout() allows you some flexibility in creating the dialog box container. If, for instance, you do not wish to
provide help text in a dialog box (in a confirmation dialog box, for example) you can suppress the help text area by
specifying FALSE in the help text display parameter of CreateLayout(). Create Resizable Layout( ) can be
used to create a resizable dialog box.
Dialog box buttons can also be suppressed if not needed. Using the example, if the dialog box did not require a Cancel
button, you could suppress it simply by specifying a blank string for the button parameter:
well as some additional controls for descriptive text and to organize the dialog box. The resulting code is shown
below:
procedure CreateDialog;
VAR
id: LONGINT;
result : LONGINT;
BEGIN
id := CreateLayout('Revise Layer Link',TRUE,'Update', 'Cancel');
CreateStaticText(id,4,'Relink to:',-1);
CreatePulldownMenu(id,5,32);
CreateGroupBox(id,6,'Link Options',TRUE);
CreateCheckBox(id,7,'Link object is locked');
CreateCheckBox(id,8,'Name Link:');
CreateEditText(id,9,'Untitled Link',26);
SetFirstLayoutItem(id, 4);
SetBelowItem (id,4,6,0,0);
SetFirstGroupItem(id,6,7);
SetBelowItem (id,7,5,0,0);
SetBelowItem (id,5,8,0,0);
SetBelowItem (id,8,9,0,0);
result := RunLayoutDialog(id,NIL);
END;
RUN(CreateDialog);
Each control that will be a part of the dialog box is defined with a call to a definition function. The definition for each
control specifies the dialog box in which it should appear, a unique number identifying the control, and the default
properties for the control. The pulldown menu, for example, is created using the function CreatePulldownMenu(),
specifying the control ID of 5 and a width of 32 characters. The Set items specify the order and location of the
identified controls (see “Defining the Dialog Box Layout” on page 81).
Creating a Custom Dialog Box | 81
Once the controls have been defined, you can optionally add help text for some or all controls. Help text provides the
user with an easy means of identifying what a control does from within the dialog box, and is usually recommended
for all but the most basic dialog boxes.
The function SetHelpString() is used to add help for a specific control. The function associates a help string with a
control; if the cursor is moved over the control when the dialog box is displayed, the associated help string will
automatically be displayed in the help text area of the dialog box. The dialog box control definition code for the help
strings is shown below:
In the example, note that we have repeated certain help text strings. We did this in order to provide useful help for the
item whether the cursor was over the actual control or over the label associated with the control. Also, help text was
omitted for the group box control; group boxes do not have associated help text.
same alignment group are aligned together. AlignItemEdge also allows you to specify whether you want an object
to shift or resize when performing the alignment.
kCancelButton:
Begin
End;
kOKButton:
Begin
End;
End;
End;
Using VectorScript Plug-ins 10
Vectorworks 8 introduced the concept of VectorScript plug‐in objects, which allow scripts to be directly integrated into
a Vectorworks workspace and be made available to any Vectorworks document. The three types of plug‐ins—menu
commands (.vsm), tools (.vst), and objects (.vso) — allow scripts to integrate into both workspace menus and tool
palettes, as well as other Vectorworks features such as the Resource Browser.
In addition to better integration into the Vectorworks environment, plug‐ins also provide script functionality for
plug‐in objects. Plug‐in objects created with VectorScript can be used to create entirely new classes of items that can
streamline and enhance the design/drafting process. They support standard Vectorworks core technologies such as
snapping, classing, and advanced object editing, giving them essentially the same status as Vectorworks built‐in object
types.
VectorScript plug‐ins also provide enhanced portability and platform independence for scripts, allowing them to be
easily moved to Vectorworks installations on either Macintosh or Windows systems.
VectorScript plug‐ins can also be localized for use in other countries. The names and strings that are displayed can be
translated to another language. Drawings containing plug‐in objects can be exchanged between users in different
countries.
Parameter Description
VectorScript Plug‐in list Lists available plug‐ins (custom plug‐ins as well as plug‐ins that ship with
Vectorworks); the icon to the left of the plug‐in name indicates the type of plug‐in (see
“Plug‐in Types” on page 84)
New Creates a new plug‐in file as described in “New Plug‐ins” on page 85
Rename Renames the plug‐in; if a workspace contains the former plug‐in name, update it to
the new name
Duplicate Creates a copy of the currently selected plug‐in; specify a name for the copy in the
Assign Name dialog box
Delete Deletes the currently selected plug‐in; this action cannot be undone
Category Assigns a plug‐in to a heading category, to easily find the plug‐in in the Workspace
Editor
Script Opens the VectorScript Editor window, to create a script that executes with the
plug‐in; see “Plug‐in Scripts” on page 87
Parameters Specifies the name, type, and default values of plug‐in parameters; see “Plug‐in
Parameters” on page 87 and “Plug‐in Parameter Types” on page 92
Strings Specifies text strings used by the plug‐in
Properties Sets plug‐in properties such as insertion conditions, mode text, and help text; see
“Plug‐in Properties” on page 88
Insert Options For object types, specifies the insertion options; see “Insertion Options” on page 92
Once a new plug‐in has been created using the Plug‐in Editor, it is made available for use in Vectorworks by adding it
to one or more workspaces with the Workspace Editor. See “Creating or Editing a Workspace” on page 765 in the
Vectorworks Fundamentals User’s Guide. Once the item has been added to a workspace, it is available to any open file
in Vectorworks without the need for importing the associated script into the active file.
Plug-in Types
A key feature of VectorScript plug‐ins is their smooth integration into the Vectorworks product interface. VectorScript
plug‐in menu commands, tools, and objects work just like any built‐in Vectorworks tool, object, or menu item. Like
built‐in menu commands, VectorScript menu commands can be set to require certain file conditions such as 2D/3D
view orientation or a selected set of items in order to activate. When a menu command or tool item is selected, the
script and any information needed by the plug‐in is loaded into memory, and the plug‐in script executes. Vectorworks
uses information provided by the plug‐in to provide the user interactions (such as constraints) and file environment
for the menu command or tool to perform its defined actions. VectorScript tools, like their built‐in counterparts, make
use of the SmartCursor and other tool‐centric Vectorworks features.
Plug-in Properties and Management | 85
Plug‐in objects have characteristics of both Vectorworks tools and Vectorworks symbols. Plug‐in objects can be added
to a Vectorworks tool palette and resemble tool items, but in use they will place instances of the object in the file much
like the symbol tool places symbols in a file. Object scripts can also be invoked through events that occur in the file.
Placed object instances can be modified with the Object Info palette to edit the parametric values that are used to
define the object, and these changes will cause the script defining the object to execute for the object to redraw. Global
file changes which force a regeneration of the file can also cause the scripts of objects placed in the file to execute.
These characteristics give plug‐in objects enormous flexibility in how they can be displayed within a file.
Plug‐in objects can also be used in conjunction with the Resource Browser to create preconfigured object instances that
need minimal editing after placement. Libraries of different object configurations based on a single plug‐in object can
be easily created and retrieved through the Resource Browser.
Plug-in Location
When Vectorworks is launched, it searches for any VectorScript plug‐ins and registers the information necessary to
activate and manage the plug‐ins. Include files are searched for in the same folder where the associated plug‐in is
located.
Vectorworks searches for plug‐ins in the following order:
1. in the user’s Plug‐Ins folder or aliases or shortcuts in the user’s Plug‐Ins folder,
2. the Plug‐Ins folder and its sub‐folders, and
3. aliases or shortcuts in the Plug‐Ins folder that point to locations outside the Vectorworks hierarchy.
The user’s Plug‐Ins folder exists in a platform‐specific location.
• Windows XP: C:\Documents and Settings\<Username>\Application Data\Nemetschek\Vectorworks\
xx\Plug‐Ins
• Windows Vista: C:\Users\<Username>\AppData\Roaming\Nemetschek\Vectorworks\xx\Plug‐Ins
• Macintosh: /Users/<Username>/Library/Application Support/Vectorworks/xx/Plug‐Ins
When plug‐ins are first created, they are always placed in the user’s Plug‐Ins folder.
When Vectorworks is launched or a workspace is activated, a plug‐in is available in the current session only if it
is located in the Plug‐ins folder, its sub‐folders, user’s Plug‐ins folder and sub‐folders, or folders referenced by
aliases (Macintosh) or shortcuts (Windows).
If a plug‐in is duplicated in more than one location, the instance that occurs first while searching the folders is the
one that is used.
The flexibility of the plug‐in location provides an advantage when upgrading from a previous version of Vectorworks.
Because third‐party plug‐ins can be stored in a folder separate from the application, they can easily be referenced
when installing the upgrade. Copying the plug‐ins folders to the current version’s folders, or referencing them with an
alias or shortcut, is all that is required when upgrading.
New Plug-ins
Specify the plug‐in type, category, parameters, options, and VectorScript code of a new plug‐in from the VectorScript
Plug‐in Editor dialog box.
To create a plug‐in:
1. Select Tools > Scripts > VectorScript Plug‐in Editor.
The VectorScript Plug‐In Editor dialog box opens.
86 | Chapter 10: Using VectorScript Plug-ins
2. Click New.
The Assign Name dialog box opens. Enter the name of the new plug‐in item and select the type of the plug‐in to
create.
Parameter Description
Name of the VectorScript Specifies the name of the new plug‐in (as well as the plug‐in file name)
Plug‐in
The plug‐in will be Describes the location of the plug‐in file
created in
Plug‐in type Select the type of plug‐in to create
Command VectorScript menu command (.vsm) plug‐ins can be used like any standard menu
command item, performing operations on the active Vectorworks document.
VectorScript menu commands can detect the view state of the active Vectorworks file,
or can determine if a selection set exists upon which the menu command can act.
Tool VectorScript tool item (.vst) plug‐ins allow scripts to be added to a Vectorworks
workspace as a tool palette item. VectorScript tools make use of the SmartCursor, and
can respond to file state conditions such as selection status or view orientation.
Objects VectorScript plug‐in objects (.vso) allow the creation of complex objects such as
standard architectural or mechanical elements, “smart” drawing components like
callouts or drawing borders, or other flexible objects which streamline the design
process. Plug‐in objects support standard Vectorworks core technologies such as
snapping, classing, and advanced object editing; they can contain up to 32,767
parameters for defining and editing the object appearance.
Point Object Point objects are defined by a single point click for placement
Linear Object Linear objects require a user‐defined line to create the basic geometry of the object
Rectangle Object Rectangle objects utilize a user‐defined rectangle to define and create the basic
geometry of the object
Plug-in Properties and Management | 87
Parameter Description
2D/3D Path Object Path objects define a user‐defined polygonal path or NURBS curve to create the basic
geometry of the object
Include File Specifies an additional file (.vss or .px) to be included with a script (see “Include
Files and Encryption” on page 138)
3. Click OK to create the plug‐in item.
Plug-in Options
Once a new plug‐in has been created and named, it is listed in the VectorScript Plug‐in Editor dialog box. Depending
on the plug‐in type, other settings are made to control its associated script, execution conditions, appearance, stored
and default parameters, and insertion options.
Plug-in Scripts
The script source code for the command, tool, or object can be created using the VectorScript Editor or a third‐party
text editor and imported into the plug‐in. The source code is saved as part of the plug‐in item.
To create script code:
1. Click the Script button from the VectorScript Plug‐in Editor dialog box.
2. Enter the script source code in the VectorScript Editor window.
3. Click OK to save the script as part of the plug‐in.
Plug-in Parameters
VectorScript commands, tools, and objects can have parameter records associated with them. These records store
persistent data between uses and provide default parameter values. A menu command which displays a dialog box,
88 | Chapter 10: Using VectorScript Plug-ins
for example, might need to store values entered by a user for later use. A tool might provide several mode options in a
popup list. Should the user wish to select a different mode for the tool, the new setting can be saved and reused on a
subsequent use of the tool item. These values can be stored in the parameter record of the menu command or tool and
retrieved later when the command or tool is selected again. Switching files will display stored values associated with
the new files or, if no parameter record exists, will display the default values of the parameter record as created by the
plug‐in item.
The parameters which define the appearance of a VectorScript object are stored in a parameter record which is
associated with each object instance placed in the file. The parameters for each object instance can be modified by
using the Object Info palette to access the values in the object parameter record. A default parameter record is also
created when the first instance of an object (or tool) is created in the active file. This default parameter record, which is
distinct from the parameter records associated with object instances, stores the object default settings with the file. It is
used when placing subsequent object instances to define the defaults for each new object instance.
For more information on plug‐in parameters, see “Plug‐in Parameter Types” on page 92.
To create a parameter record:
1. Click the Parameters button from the VectorScript Plug‐in Editor dialog box.
The Parameters dialog box opens.
2. Click New to create each parameter record and its settings.
For linear objects, the LineLength parameter is displayed, which contains the axis length of the linear object.
For rectangular objects, both the LineLength (the initial length of the object instance) and BoxWidth (the initial
width of the object instance) parameters are displayed. New default values can be specified for these
parameters, but they cannot be deleted.
For details on specific plug‐in parameter types, see “Parameter Types” on page 93.
3. Click OK to save the parameters.
Plug-in Properties
Property settings allow plug‐ins to behave like standard Vectorworks menu commands, tools, and objects. These
settings control behavior of the plug‐in with respect to the state of the file (selection status, view orientation) as well as
define the help text to display.
The properties available depend on the plug‐in type.
Command Properties
To set properties for commands:
1. From the VectorScript Plug‐in Editor dialog box, select the command plug‐in and click Properties.
The Command Properties dialog box opens.
Plug-in Properties and Management | 89
2. Select the availability options and enter the help text for the plug‐in.
Parameter Description
Availability Options Sets when the command is available for execution
Drawing State Lists the drawing conditions which can be selected as a condition for plug‐in
availability
Require Requires the drawing state condition to exist for the command to be active
Prohibit Deactivates the command if the drawing state condition exists
Ignore Ignores the drawing state condition
Help Specifies the menu command help text; help text describing the menu command
displays when the cursor pauses over the command (currently, this is only available
on Macintosh)
Contextual Help ID Specify a unique ID number for the help topic
If a menu command should act only on a single selected object, for example, availability options would be set to
require object selection, but prohibit multiple selection. The menu command is disabled when the drawing state
does not match the indicated option settings.
3. Click OK to save the new settings for the plug‐in.
Tool Properties
To set properties for tools:
1. From the VectorScript Plug‐in Editor dialog box, select the tool plug‐in and click Properties.
The Tool Properties dialog box opens.
2. Select the Mode bar (Tool bar in versions of Vectorworks 2008 and above) text, icon, availability options, help ID,
and help text for the plug‐in.
90 | Chapter 10: Using VectorScript Plug-ins
Parameter Description
Mode Bar String Specifies the descriptive text to display for modes on the Tool bar; usually this
includes the name of the tool, and it can include text indicating an action for the user
to perform
Icon The default icon can be replaced by a custom icon, if desired. With a third‐party icon
editor, create an 8‐bit image, centered in an area 24 pixels wide by 18 pixels high. Save
the icon in .png format, and click Import PNG Icon to import it.
Activation Options Controls the projection requirements and the conditions under which the object script
code executes
Projection Determines what view projection must be active. If the required projection is not
active, the user is prompted before switching the view to the correct projection.
Execute Script Tools are set by default to execute immediately when selected. In some cases,
however, it may be desirable to have the script execution wait for mouse movement
(such as a tool which draws interactively based on user mouse movement).
Contextual Help ID Specify a unique ID number for the help topic
Help Specifies the help text to display when the cursor pauses over the tool icon in a palette
3. Click OK to save the new settings for the plug‐in.
Object Properties
To set properties for objects:
1. From the VectorScript Plug‐in Editor dialog box, select the object plug‐in and click Properties.
The Object Properties dialog box opens.
2. Select the Tool bar text, icon, availability options, help ID, and help text for the plug‐in.
Plug-in Properties and Management | 91
Parameter Description
Mode Bar String Specifies the descriptive text to display in the Tool bar; usually this includes the name
of the object, and it can include text indicating an action for the user to perform
Icon The default icon can be replaced by a custom icon, if desired. With a third‐party icon
editor, create an 8‐bit image, centered in an area 24 pixels wide by 18 pixels high. Save
the icon in .png format, and click Import PNG Icon to import it.
Projection Determines what view projection must be active. If the required projection is not
active, the user is prompted before switching the view to the correct projection.
Execute Script Objects are set by default to execute immediately when selected. In some cases,
however, it may be desirable to have the script execution wait for mouse movement
(such as a tool which draws interactively based on user mouse movement).
Default Class Specifies the default class for the object upon insertion; if the class does not exist when
the object is placed, the class is automatically created
Contextual Help ID Specify a unique ID number for the help topic
Help Specifies the help text to display when the cursor pauses over the object icon in a
palette
92 | Chapter 10: Using VectorScript Plug-ins
Parameter Description
Script Execution By default, object geometry will only be recalculated if the object parameters or
control points are edited. When object geometry is recalculated, file default settings
for attributes such as font, text size, or line color will be reapplied to the object. If any
of these settings have been modified since the object was placed or last edited,
changes in the appearance of the object may occur. The default reset options allow
objects to be manipulated without invoking object regeneration.
Reset Only calls object scripts for object regeneration when the object needs to
regenerate itself to match the current object parameters. The script is called whenever
the object parameters have changed. Additionally, for instances where it is important
for the object to recalculate (for example, windows placed in a wall), the script can
cause geometry to be recalculated when the object is rotated (Reset on Rotate) or
moved (Reset on Move).
Alternatively, the plug‐in script can become an event handler (With Script‐Specified
Events); scripts must then respond to a small set of application events. For samples
and documentation on event handling scripts, go to www.nemetschek.net and access
the Support > Customization > VectorScript > Examples area.
3. Click OK to save the new settings for the plug‐in.
Insertion Options
Objects, like symbols, can be assigned predefined insertion options for document placement. These options allow
objects to properly interact with walls or other advanced Vectorworks object types. Command and tool plug‐ins do not
have insertion option settings.
To set insertion options for plug‐in objects:
1. From the VectorScript Plug‐in Editor dialog box, select the object plug‐in and click Insert Options.
The Insertion Options dialog box opens.
2. Select the wall insertion option settings for the object. See “Creating New Symbols” on page 183 in the
Vectorworks Fundamentals User’s Guide.
For objects which do not require insertion options, leave the options at the default settings.
Parameter Types
VectorScript provides several parameter field types for use with plug‐ins:
94 | Chapter 10: Using VectorScript Plug-ins
• Integer
• Boolean
• Number
• Text
• Popup
• Radio Button
• Dimension
• X‐Coordinate
• Y‐Coordinate
• Control Point
• Static Text
Parameter records can have multiple parameter fields of the same type, or combinations of parameter fields of
different types. The following sections document each parameter type in detail.
Integer
Integer parameters store a single INTEGER data value.
An integer parameter value is displayed in the Object Info palette in an editable field, and can be edited as desired.
Integer parameter fields support calculations in the field, fractional values entered into an integer parameter field will
be rounded to the nearest value.
Integer parameters do not support unit marks or unit conversion.
Boolean
Boolean parameters store a single BOOLEAN data value.
A boolean parameter is displayed in the Object Info palette as a check box, with the state of the check box indicating
the TRUE-FALSE state of the value (TRUE = checked, FALSE = unchecked).
Boolean parameters do not support unit marks or unit conversion.
Plug-in Parameter Types | 95
Number
Number parameters store a single REAL data value.
A number parameter value is displayed in the Object Info palette in an editable field, and can be edited as desired.
Number parameter fields support calculations in the field, and fractional values entered into a number parameter field
will be displayed using the current units fractional display setting.
Number parameters do support unit marks or unit conversion.
96 | Chapter 10: Using VectorScript Plug-ins
Text
Text parameters store a single string data value. The stored value may be up to 255 characters in length.
A text parameter value is displayed in the Object Info palette in an editable field, and can be edited as desired.
Popup
Popup parameters store a single STRING data value that is selected from a predefined list of values. The list of
available values is defined in the parameter definition dialog box, and cannot be modified during script execution.
Popup parameter values are displayed in the Object Info palette as popup menu listing the defined value options. The
active parameter value (the value which is stored in the parameter) is indicated by the value displayed in the popup
when the control is not selected, and by a bullet next to the item when the control is selected. To modify the value,
select the desired parameter value from the popup control.
Plug-in Parameter Types | 97
Radio Button
Radio button parameters store a single STRING data value that is selected from a predefined list of values. The list of
available values is defined in the parameter definition dialog box, and cannot be modified during script execution.
Radio button parameter values are displayed in the Object Info palette as a series of radio buttons in a group box, with
one radio button for each defined value. The active parameter value (which is stored in the parameter) is indicated by
the selected radio button. To modify the value, select the radio button corresponding to the desired value.
Dimension
Dimension parameters store a dimension data value as a REAL numeric value.
A dimension parameter value is displayed in the Object Info palette in an editable field, and the value can be edited as
desired. Dimension parameter fields support calculations in the field, and fractional values entered into a dimension
parameter field will be displayed using the current unit’s fractional display setting.
Two default values can be specified—one for Imperial units, and one for Metric. The appropriate dimension is
automatically displayed for the plug‐in depending on the file’s units setting. Entering two default values is not
required; if one default is left blank, the other value is converted to the appropriate value for the units in the file.
Plug‐ins from versions of Vectorworks earlier than 12 are automatically saved with the dual default value
capability when the plug‐in is edited. The single existing default dimension, if it has a unit, is automatically
saved in the appropriate default value field (Imperial or Metric).
Dimension parameters support the use of unit markers with values; values stored in one unit format are automatically
converted to an equivalent value if the document unit setting is modified. Units are not required; values without units
assume the drawing units and are not converted.
Dimension parameters are not sensitive to changes in the user origin of a document.
98 | Chapter 10: Using VectorScript Plug-ins
X-Coordinate
X‐coordinate parameters store a coordinate data value as a REAL numeric value.
A coordinate parameter value is displayed in the Object Info palette in an editable field; the value can be edited as
desired. Coordinate parameter fields support calculations in the field, and fractional values entered into a coordinate
parameter field will be displayed using the current unit’s fractional display setting.
Coordinate parameters support the use of unit marks with values; values stored in one unit format will be
automatically converted to an equivalent value if the document unit setting is modified.
Coordinate parameters are sensitive to changes in the user origin of a document, and are designed to be used with
geometric data that is related directly to locations within a Vectorworks document. Values displayed in coordinate
fields will be corrected for any changes in the document user origin.
Y-Coordinate
Y‐coordinate parameters store a coordinate data value as a REAL numeric value.
A coordinate parameter value is displayed in the Object Info palette in an editable field; the value can be edited as
desired. Coordinate parameter fields support calculations in the field, and fractional values entered into a coordinate
parameter field will be displayed using the current unit’s fractional display setting.
Coordinate parameters support the use of unit marks with values; values stored in one unit format will be
automatically converted to an equivalent value if the document unit setting is modified.
Coordinate parameters are sensitive to changes in the user origin of a document, and are designed to be used with
geometric data that is related directly to locations within a Vectorworks document. Values displayed in coordinate
fields will be corrected for any changes in the document user origin.
Control Points
Control point parameters are a specialized parameter type designed to create control points in plug‐in objects. A
control point is similar to a selection handle and allows the user to click and drag to reshape the object. When created,
a control point parameter consists of two linked coordinate parameters. The two parameters correspond to x‐ and
y‐coordinate fields for the control point.
Control point parameters are displayed in the Object Info palette as a pair of editable coordinate fields; the values can
be edited as desired. Control points, like coordinate fields, support calculations in the fields. Fractional values entered
into a control point parameter field will be displayed using the current unit’s fractional display setting.
Control point parameters support the use of unit marks with values; values stored in one unit format will be
automatically converted to an equivalent value if the document unit setting is modified.
Plug-in Parameter Types | 99
Control point parameters are sensitive to changes in the user origin of a document, and values displayed in the field
will be corrected for any changes in the document user origin.
Control point fields can be renamed by entering a display name in the alternate name field of the parameter. This
value will be used as the control label in the Object Info palette; when referring to the parameter in a script, use the
actual definition name of the parameter.
Static Text
Static text parameters are used to display information on the Object Info palette. The information is for display
purposes, and cannot be edited by the user. This type of parameter might display a calculated field, like the area or
volume of an object, or some other property. Each instance of the object in a drawing can display a different value for
this parameter.
P<name of parameter>
Parameter names should contain underscores representing any embedded spaces in the parameter name. For example,
a dimension parameter named Space Width would be referenced in a script as:
PSPACE_WIDTH
Parameter references can be used to assign values to other identifiers in a script. Supported identifiers include
variable, array, array element, and structure member identifiers. For example, assigning the value in the parameter to
a variable would be defined as:
100 | Chapter 10: Using VectorScript Plug-ins
sp_width:= PSPACE_WIDTH;
Parameter references can also be used like constants in expressions or function arguments. For example, valid uses of
Space Width parameter would include:
totalWidth:= 5 * PSPACE_WIDTH;
CalculateTotal(PSPACE_WIDTH,2);
Parameter references should always be treated as constant values. Parameter references do not accept value
assignments, and parameter reference values cannot be modified.
BEGIN
resultStatus:= GetCustomObjectInfo(objName,objHd,recHd,wallHd);
In the example, GetCustomObjectInfo() is called to obtain the name of the object and a handle to both the object
instance and its associated parameter record. This information is then used with SetRField() to write the value to
the parameter record field.
Note that when writing values to the parameter record, the actual name of the field, not the parameter reference, is
used. Parameter references should only be used for retrieving data from the parameter record.
The example also points out one additional requirement for using SetRField(). In the example, the value in
sp_width is a REAL, but SetRField() requires a STRING argument for the value being assigned to the record field.
In this case, it will be necessary to convert the dimension value to a STRING for compatibility with the function call.
The parameter record will convert the value back to the appropriate data type when it is stored.
Plug-in Parameter Types | 101
The method for writing values to the parameter records of menu commands and tool items is almost identical to the
method used for objects. In the case of menu commands and tool items, the function GetPluginInfo() should be
used to obtain the plug‐in name and a handle to the parameter record. The example below illustrates how the function
is used with a menu command:
BEGIN
...
...
IF GetPluginInfo(cmdName,pRecHd) THEN
offvalue:= GetField(5);
numlines:= GetField(6);
cmdHd:= GetObject(cmdName);
SetRField(cmdHd,GetName(pRecHd),'Offset',Num2StrF(offvalue));
SetRField(cmdHd,GetName(pRecHd),'Lines',Num2Str(0,numLines));
END;
...
...
END;
In the example, GetPluginInfo() is used to obtain the name of the menu command and a handle to the parameter
record. This information is used with SetRField() to write values to the parameter record of the menu command.
Parameter records for menu commands and tool items are very useful for storing information between uses of the
command or tool item. For example, if a user modifies the default settings of a tool item, this information can be stored
and reused on subsequent uses of the tool.
Like objects, records for menu commands and tool items are stored with a Vectorworks file; switching files may
cause the default settings for a command or tool item to change.
BEGIN
...
resultsStatus := GetCustomObjectInfo(objName,objHd,recHd,wallHD);
IF resultStatus THEN BEGIN
Like the plug‐in object example above, plug‐in menus and tools that use parameters can use
SetParameterVisibility() and EnableParameter().
BEGIN
...
...
IF GetPluginInfo(cmdName,pRecHd) THEN
cmdHd:= GetObject(cmdName);
EnableParameter(objHd, ‘Offset’. FALSE);
SetParameterVisibility(objHd, ‘Lines’. FALSE);
END;
...
...
END;
Creating Scripts
Vectorworks provides several methods for creating, managing and using scripts. The most basic of these methods is to
create a Vectorworks document and select the File > Export > Export VectorScript command. The command creates a
script which can be run by the File > Import > Import VectorScript command, or by selecting the file in the Resource
Browser, and then selecting Run from the Resources menu.
The traditional method for storing scripts, which has been a feature of Vectorworks since its original release as
MiniCad, is in document scripts. Document scripts are stored with individual documents in script palettes, which
organize the scripts and can be displayed or hidden as needed. Both document scripts and script palettes can be
created and accessed from the Resource Browser.
Beginning with Vectorworks 8, scripts can also be created and stored as plug‐ins. Plug‐ins are used as a component of
a workspace, and can be accessed by any document. Scripts in plug‐ins can be used as menu items, tools, or parametric
objects. Plug‐ins are created and maintained using the plug‐in editor, which is accessed by selecting Tools > Scripts >
VectorScript Plug‐in Editor.
2. Select Open from the Resources menu. The VectorScript Editor opens, displaying the script source code.
To edit an existing custom plug‐in, open the plug‐ins editor, select the plug‐in to be edited, and click the Script
button (only unencrypted plug‐in scripts can be edited).
VS Compiler Mode
The VS Compiler Mode command is a convenient way for advanced VectorScript developers to speed up the
development process.
The VS Compiler Mode command is only available in the Design Series.
By default, the scripts of VectorScript plug‐in objects, tools, and menus are compiled once and stored in memory. The
object, tool, or menu command memory cache is executed when the script is invoked. However, in VS Compiler mode,
the script is compiled each time so that script changes are executed immediately and the developer does not need to
restart the application to view changes.
To set VS Compiler mode:
1. Select Tools > Scripts > VS Compiler Mode.
2. A VectorScript message indicates that scripts will be compiled at each execution.
3. Select the command again to exit VS Compiler mode.
Font Settings
Current line number
Compile script
Editor menu
Editor Menu
The VectorScript Editor Menu provides access to the extended features of the editor.
Procedure
The Procedure command provides access to a browser listing all the functions found in the VectorScript API.
Functions are listed by category and provide a function prototype as well as a brief description of what operation is
performed by the function.
The VectorScript Editor | 107
Inquiry
The Inquiry command provides a listing of all functions which use search criteria. When used in conjunction with the
Criteria option (see below), custom queries or selections can easily be defined in a script.
Criteria
The Criteria command provides a convenient method of defining search criteria for use in scripts. The dialog box,
which is similar to the Custom Selection dialog box, allows criteria to be chosen from a listing of available search
options.
Tool / Attribute
The Tool / Attribute command provides a way of saving the current tool and attribute state information into a script.
Parameters
The Parameters command provides access to a plug‐in objects’ parameter list for editing.
Text File
The Text File command allows script source code to be imported from external text files.
Font Settings
Click Font Settings to open the Format Text dialog box, where the font and font size of the text in the VectorScript
Editor window can be changed. Changes to the text formatting apply to all of the text in the Editor (formatting a
selection of text is not possible).
Compile Script
The Compile Script button allows a script to be compiled directly from the VectorScript Editor without the need to
execute the script. If errors exist within the script which prevent successful compilation, they will be displayed and can
be resolved without the need to exit the script editor.
Line Number
The current position of the cursor within the edit field of the VectorScript Editor is indicated by the line number
displayed in the editor window.
VectorScript Errors
If an error occurs during script execution, the Script Error dialog box opens.
108 | Chapter 11: VectorScript Development Tools
To handle script errors:
1. From the Script Error warning, click the View Error Output button.
2. The Script Errors dialog box opens, displaying the nature of the error and the line(s) where the error occurred.
3. To edit the script, select the offending line and click Edit Script, or double‐click a script line. The VectorScript
Editor opens for making corrections to the script.
Plug-in list
Plug-in management
Plug-in options
and settings
The main editor window displays a listing of all available plug‐ins in the Vectorworks installation. The dialog box also
provides options for managing plug‐in files, as well as for accessing the various settings and options available in each
plug‐in.
Managing Plug-ins
New
To create a new plug‐in object, click the New button. When prompted, enter the name and select the type of plug‐in to
be created.
Plug‐in names are limited to twenty characters in length. The appropriate plug‐in extension will be appended to the
plug‐in name. Plug‐ins are saved in the location indicated so that they are not overwritten when installing a new
version of Vectorworks.
Rename
To rename an existing plug‐in, select a plug‐in from the list and click the Rename button. Enter the new name for the
plug‐in and click OK.
Duplicate
To create a copy of an existing plug‐in, select a plug‐in from the list and click the Duplicate button. Enter a name for
the plug‐in and click OK.
Delete
To delete an existing plug‐in, select a plug‐in from the list and click the Delete button.
Category
To specify a category for a plug‐in, select a plug‐in from the list and click the Category button. When prompted, enter
the name of category that will be associated with the plug‐in.
The plug‐in category is the heading that the plug‐in may be found under in the Workspace Editor.
Properties
To modify the properties associated with a plug‐in item, click the Properties button. The Properties dialog box specific
to the type of the selected plug‐in item will be displayed.
For more details on specific plug‐in properties, see “Using VectorScript Plug‐ins” on page 83.
Parameters
To create or modify parameters associated with the plug‐in parameter record, click the Parameters button. The
Parameters dialog box will be displayed, allowing specific parameter settings to be edited or created.
The VectorScript Debugger | 111
Parameter records may be created for any plug‐in object type. Parameter records for object plug‐ins store data which
defines the display characteristics of the object; this information can also be edited from the Object Info palette.
Parameter records for custom tools and menu items store default and status related data for the item; this information
can only be edited through the parameters dialog box.
For more details on plug‐in object parameters, see “Using VectorScript Plug‐ins” on page 83.
Insertion Options
To set insertion options for object plug‐ins, click the Insert Options button. The Insertion Options dialog box opens,
where insertion options for the object can be specified.
Insertion options cannot be specified for menu command or tool item plug‐ins. For more details on insertion options
available for object plug‐ins, see “Insertion Options” on page 92.
PROCEDURE MakeCircle;
{$DEBUG}
VAR
x1,y1,x2,y2,radius : REAL;
BEGIN
GetPt(x1,y1);
GetPtL(x1,y1,x2,y2);
radius:= Distance(x1,y1,x2,y2);
Oval(x1 - radius,y1 + radius,x2 + radius,y2 - radius);
112 | Chapter 11: VectorScript Development Tools
END;
Run(MakeCircle);
This launches the VectorScript debugger and displays the window as shown:
The VectorScript debugger allows a script to be executed in a line‐by‐line fashion, also known as ʺsteppingʺ through
the source code. The debugger performs this task beginning at the first line of the script and continuing through each
line until the end of the script is reached.
When the debugger is launched, storage for variables and constants is defined and script execution is paused at the
first line of code in the script body. The debugger window is then displayed, providing a wide array of information on
the script and the current state of execution.
The VectorScript Debugger | 113
Debugger controls
Message area
Script calling chain
The debugger window contains controls for managing script execution, as well as several areas for displaying various
data about the script and the state of execution.
Debugger Controls
The debugger controls allow the execution of the script to be controlled during the debugging process. Script
execution can be started, stopped, paused, or advanced one line at a time.
Pause script
Kill script
Step over
See “Controlling Execution” on page 114 for details on controlling script execution in the debugger.
114 | Chapter 11: VectorScript Development Tools
Message Pane
The message pane displays information about the script. These messages may include prompts for user interaction
with the script, script status information, or errors encountered in script execution.
Controlling Execution
Running a Script
To run a script in the debugger, click the Run button.
Running a script here is identical to running a script from a script palette or plug‐in; when the script has completed
execution, the debugger window will close.
Running scripts is primarily used in conjunction with setting a breakpoint in the debugger. For details on setting and
using breakpoints, see “Using Breakpoints” on page 116.
The Step Into button is used when a statement containing a call to a user‐defined subroutine is reached. Whereas the
Step Over button will execute all the code contained within the subroutine and move to the next statement in the
calling function, Step Into will advance script execution to the first statement within the subroutine body.
The Step Into button performs a Step Over action with all other statements.
When stepping out of a subroutine, all statements which follow the current script location will be executed, and script
execution will advance to the next statement in the calling routine.
The Auto‐Step button will automatically advance the script at a speed determined by the Auto‐Step slider control.
The Pause Script button will stop auto‐step execution at the current execution location in the script. Script execution
can be resumed by clicking the Auto‐Step button.
The Pause Script button can also pause execution of scripts in infinite loops; in some instances, however, Pause Script
may not be able to stop such loops.
116 | Chapter 11: VectorScript Development Tools
The Kill Script button will immediately terminate script execution. After the Kill Script button is pressed, the
debugger window will close.
Using Breakpoints
A breakpoint suspends script execution and transfers control of the script to the debugger. When a breakpoint is
encountered, execution is suspended just prior to the breakpoint, and the script execution pointer is positioned at the
breakpoint location.
Breakpoints are often used in order to run scripts and stop them just prior to a statement or statements that are to be
debugged. Once the script has stopped at a breakpoint, it may be stepped through manually or by using the auto‐step
feature.
Setting a Breakpoint
To set a breakpoint in the debugger, click the dash in the narrow column on the left side of the script source code pane.
The new break point will be indicated by a small diamond at the break location.
Click to set breakpoint in script
Breakpoint is
indicated by a
diamond
Once a breakpoint has been set, the script can be executed using the Run Script button. Script execution will pause
when the breakpoint is reached, as indicated by a highlighted breakpoint and execution pointer arrow. The message
pane of the debugger will also indicate that a break point has been reached.
The VectorScript Debugger | 117
Message indicating
status
Execution paused at
breakpoint
To continue execution, click either the Run Script, Step Over/Into/Out, or Auto‐Step buttons.
Breakpoints which have been placed in a looping statement will cause the script to stop each time the breakpoint is
encountered. When used in conjunction with the Run Script or Auto‐Step buttons, such breakpoints can be used to
observe conditions occurring within a loop during execution.
Care should be exercised when placing breakpoints within branching statements such as IF..THEN or CASE
statements. If the breakpoint is in a branch outside the path of execution, the script will continue to execute.
Clearing Breakpoints
To clear a breakpoint in the debugger, click the diamond indicating the breakpoint location while script execution is
stopped or paused. The breakpoint is removed from the script.
Variables declared in
script are displayed in
data pane
Vectors, array elements, and structure members can also be observed in the data display pane during script execution.
Items containing more than one storage location are shown with a disclosure triangle to the left of the item name. To
view the storage locations contained within the item, click the disclosure triangle; the individual locations and the
values contained in them will be displayed below the item name.
The VectorScript Debugger | 119
The view within data pane can be resized to accommodate data display. To resize the value display, move the cursor
over the divider line, and then drag the divider to the desired location.
120 | Chapter 11: VectorScript Development Tools
Numeric and Data Formats A
Units and Numeric Values in Scripts
Numeric values which are associated with unit markings follow these rules:
• VectorScript will scan for all legal predefined unit marks when parsing numeric values. If illegal characters are
found after numeric values, a VectorScript warning will be generated.
• VectorScript will not scan for user‐defined unit marks.
• Numeric values in VectorScript which are bound to a unit marking will be sized to be accurate to their unit mark
within the current units setting of the active document. For example:
will always draw a rectangle that is 14” on a side independent of the units setting, and
will always draw a rectangle which is 14 centimeters on a side, independent of the document unit setting.
• Numeric values which are not bound to a unit marking will be sized to the current units setting of the document.
For example:
will draw a rectangle 14 document units on a side. If the current units setting is Feet, the rectangle will be 14 feet
on a side; if the units setting is millimeters, the rectangle drawn will be 14 mm on a side.
• Numeric constants are bound to any specified unit mark. For example:
CONST
kX = 5.5cm;
will be bound to and retain its centimeter unit marking.
Rect(2',0',0',2');
will draw a rectangle with the top left corner at (2',0') and the bottom right corner at (0',2').
In relative mode, values are assumed to be relative offsets from the current drawing pen position in the active
document. Using the example above:
Rect(2',0',0',2');
122 | Appendix A: Numeric and Data Formats
If the pen position prior to the call was (4',2'), the call would draw a rectangle with its top left corner located at
(4',4') and its bottom right corner located at (6',2'). Additional drawing calls while in this mode would be
relative to the last function call which positioned the drawing pen.
VectorScript uses two calls, Absolute() and Relative(), to explicitly set the drawing mode of the document.
These calls can be used to set the document draw mode and draw objects using offset rather than absolute values. For
example:
Relative;
MoveTo(2",2");
Poly(1",0",0",1",-1",0",0",-1");
will draw a square polygon 1ʺ on a side with the lower left corner located at (2",2"). The same calls made without a
call to Relative() will draw a different polygon using absolute coordinate locations.
Once the relative mode is set, it will remain active until a call to Absolute() or when the script finishes execution. Be
sure to reset the drawing mode to the desired state in order to ensure correct results from your script.
Distance-angle Mode
VectorScript also supports an additional numeric mode for drawing objects, distance‐angle mode. With distance‐angle
mode, coordinate locations are defined using a distance and a direction angle, similar to polar coordinates. When
specifying a distance‐angle pair, the distance is specified in place of the x‐coordinate, and the angle is specified in place
of the y‐coordinate. For example:
Relative;
MoveTo(2",2");
Poly(1",0",0",1",-1",0",0",-1");
could be specified as
Relative;
MoveTo(2",2");
Poly(1",#0d,1",#90d,1",#180d,1",#270d);
In distance‐angle mode, the pound ( # ) sign is used to denote that an angle value follows.
VectorScript supports a wide array of formats for specifying the angle component of a distance‐angle pair. The table
below lists the supported angle formats.
When using surveyors’ units, be sure to use AngleVar() and NoAngleVar() to ensure that the bearing values are
interpreted correctly.
theInt:=23456;
Write(theInt:3);
will write '23456' to the file.
When MinWidth exceeds the width of the formatted value, spaces are prepended the value:
124 | Appendix A: Numeric and Data Formats
theInt:=23456;
Write(theInt:7);
will write ' 23456' to the file.
REAL Values
In the following example, a combination of MinWidth and DecPlaces values are used to format the value string. The
value displays a total character length (including the decimal point) of six characters, and displays two‐place decimal
precision. The value is rounded to meet the specified display settings:
theReal:=789.128;
Write(theReal:6:2);
will write '789.13' to the file.
If the DecPlaces setting exceeds the precision of the value to be displayed, zeroes will be appended to bring the value
up to the DecPlaces setting. MinWidth is overridden by both the value and the DecPlaces setting:
theReal:=789.128;
Write(theReal:2:6);
will write '789.128000' to the file.
will write 'This is' to the file.
Write('VectorScript':6);
will write 'Vector’ to the file.
Write('VectorScript':16);
will write ' VectorScript' to the file.
Search Criteria B
Search criteria are designed for use with VectorScriptsʹ criteria API and with worksheets to filter and locate objects by
the specified attribute values. Search criteria use the attributes of Vectorworks objects (layer, class, color, lineweight,
etc.) as a means of selecting and manipulating subsets of items within the file.
Attribute Types
Markers (AR)
The marker attribute type will search for the indicated marker style. The search value should be one of the supported
marker style flag selector values (in a range of 0 – 27).
Class (C)
The class attribute type will search for objects assigned to the specified class. The search value should be a STRING
value which is up to 64 characters in length (literals and variables are supported).
Layer (L)
The layer attribute type will search for objects on the specified layer. The search value should be a STRING value which
is up to 64 characters in length (literals and variables are supported).
(R IN ['Part Data'])
The record name must be a literal STRING value.
Visibility (V)
The visibility attribute specifier will search for objects based on their visibility status. The search value is a BOOLEAN
value indicating the visibility state (TRUE for visible, FALSE for invisible).
Specialized Searches
In addition to the standard attribute types available for use in search terms, VectorScript also provides specialized
search attribute types for additional flexibility in searching a file.
(<record name>.<field name>[< = | <> | > | >= | < | <= ><search value>])
The record and field names are STRING values and should be enclosed in single quotes. Any one of the optional
comparison operators can be used to focus the search on a specific subset of items which have the attached record. For
example:
128 | Appendix B: Search Criteria
Location (LOC)
The LOC specifier finds objects that are located within the bounds of a named object, like a fence.
{$INCLUDE}
The include directive instructs the compiler to insert source code from an external file at the position of the include
directive statement. The syntax for an include directive is:
{$DEBUG}
The debug directive instructs the compiler to launch the VectorScript debugger when compiling and executing the
script. The debugger may then be used to observe and control script execution during script development. The syntax
for the debug directive is:
{$DEBUG}
The directive may be positioned anywhere within the main block of the script to invoke the debugger.
Details on using the debugger may be found in “The VectorScript Debugger” on page 111.
{$NAMES}
The names directive instructs the compiler to recognize only the identifiers which are valid for the Vectorworks
version specified in the compiler directive. Identifiers screened by this directive include procedure, function, and
constant identifiers. The syntax for the names directive is:
Identifiers which are not defined for the specified version of the product will generate a VectorScript error. The names
directive is intended for use in testing compatibility of scripts with different versions of Vectorworks.
{$STRICT}
The strict directive instructs the compiler to recognize observe syntax and semantic rules which are valid for the
Vectorworks version specified in the compiler directive. The syntax for the strict directive is:
by other objects or features.
Script Encryption E
VectorScript provides support for protecting scripts by encryption. Encrypted scripts can then be distributed for sale
or other use without making the script source code available for unintended reuse or modification. VectorScript
supports encryption of plug‐ins, document scripts, and standalone script files.
VectorScript encryption is non‐reversible, meaning that once a script is encrypted, it cannot be decrypted for further
editing or modification. Scripts should always be saved to a separate file or location prior to encryption to prevent loss
of script code.
Encrypting Scripts
Plug-ins
To encrypt a plug‐in:
1. Select Tools > Scripts > VectorScript Plug‐in Editor. In the VectorScript Plug‐in Editor, select the plug‐in to be
protected from the editor list.
2. Use the following key combination, pressing the keys simultaneously:
Macintosh Caps Lock+Shift+Option+Command
Windows Shift+Ctrl+Alt
3. Click the Script button in the Editor. Confirm twice that the plug‐in should be protected.
Macintosh Caps Lock+Shift+Option+Command
Windows Shift+Ctrl+Alt
3. Double‐click the selected script in the palette. Confirm twice that the script should be protected.
PROCEDURE Remote_Sub;
VAR
j:INTEGER;
BEGIN
AlrtDialog('This is the include function');
END;
The calling script then referenced the include file as shown:
PROCEDURE EncryptExample1;
VAR
i:INTEGER;
s:STRING;
{$INCLUDE myinclude.vss}
BEGIN
Remote_Sub;
END;
Run(EncryptExample1);
If the script above were encrypted, the subroutine Remote_Sub would remain in the include file. It would be called as
needed by the EncryptExample1 script, and the include file would also need to be present in order for
EncryptExample1 to execute properly. If we were to change the name of the include file and modify the calling
script as shown:
PROCEDURE EncryptExample1;
VAR
i:INTEGER;
s:STRING;
{$INCLUDE myinclude.px}
BEGIN
Remote_Sub;
END;
Run(EncryptExample1);
140 | Appendix E: Script Encryption
In this instance the code from myinclude.px would be copied into the calling script at the location of the include
statement, and the entire script would then be encrypted. The encrypted script would require no additional files to
execute properly, and the original code in the file myinclude.px would be untouched.
Include files should not be encrypted as standalone documents separate from a script. Files encrypted in such a
manner cannot be referenced from another script, and cannot be decrypted.
Index
Symbols list box 73
list browser 73
{$DEBUG} 111, 133
marker popup 74
{$INCLUDE} 133 pattern popup 74
{$NAMES} 133 pulldown menu 74
{$STRICT} 134 push button 75
radio button 75
A separator 75
slider 76
Accessing parameters from scripts 99 standard icon 77
Actual parameters 60 static text 76
Alerts, presenting swap 77
dialog boxes 77 tab pane 78
predefined 65 Custom dialog boxes 65
Arrays (VectorScript)
dynamic 20 D
index of 19
static 19 Data types
BOOLEAN 16
CHAR 16
B HANDLE 17
Block scope 61 INTEGER 15
Branching in VectorScript 48 LONGINT 15
REAL 16
STRING 16
C VECTOR 17
CASE 50 Debugger
Comments 7 controlling scripts 114
Compound expressions 33 controls 113
CONST block 14 using breakpoints 116
Constant definition 14 Delimiters 7
Constants 14 Development tools
Control plug‐in editor 108
check box 66 VectorScript debugger 111
color palette 67 VectorScript editor 105
color pop‐up 67 Dialog
edit integer 68 controls 66
edit real 68 events 66
edit text 68 Dialog box
edit text box 69 controls 66
gradient slider 69 creating custom 78
group box 69 Document script 103
image 70 creating 103
image pane 70 editing 103
image popup 70 Dynamic arrays 20
line attribute popup 71 ALLOCATE 21
line style popup 72 dimensioning 21
line weight popup 72 extended string support with CHAR arrays 23
142 | Index
one‐dimensional dynamic array 20 M
performance considerations 23
Menu commands (.vsm) 83
two‐dimensional dynamic array 20
O
E
Objects (.vso) 83
Encryption 137
Operand 33
Errors 107
Operators 33
Expressions
arithmetic 34
arithmetic operators 34
array access 38
associativity 34
assignment 38
comparison operators 36
associativity 34
complex expressions 33
binary 33
logical operators 37
comparison 36
operator precedence 34
logical 37
simple expressions 33
member access 39
precedence 34
F unary 33
Floating‐point values 16
Font, editor 107 P
FOR..DOWNTO 46 Parameter fields 93
FOR..TO 46 Parameter list 55
Formal parameters 60 Parameter records 93
Fundamental types 15 Plug‐in
creating 85
G editor 108
function 84
Global scope 63
location 85
objects 83
I parameters 92
Identifiers 9 setting options for 87
IF..THEN 48 upgrading 85
Include files 138 Program block 61
K R
Keywords 10 REPEAT..UNTIL 47
Reserved 10
L Reserved words 10
Return value 57
Literals 8
BOOLEAN literals 9
floating‐point literals 8 S
integer literals 8 Script palette 103
NIL 9 Search attribute type specifier 125
string literals 9
Search criteria 125
Looping in VectorScript 45
Search value 125
Index | 143
Setting parameter values from scripts 100 VectorScript Editor 105
Source‐level debugger 111 font settings 107
Special symbols 7, 11 menu 106
Statements VectorScript error 107
FOR..DOWNTO 46 VS Compiler Mode command 105
Statements in VectorScript
assignments 41 W
compound 44 WHILE..DO 46
constant ranges with CASE 51
control expressions in CASE statements 50
FOR..TO 46
GOTO 45
IF..THEN 48
procedures 44
REPEAT..UNTIL 47
WHILE..DO 46
Static arrays 19
accessing an array element 20
one‐dimensional static array 19
two‐dimensional static array 20
Structures
member access 30
members 29
Subroutines in VectorScript 55
Symbols 7
T
Text, static 99
Tokens 7
Tool (.vst) 83
TYPE block 29
U
User‐defined
function 57
procedures 55
types 15
V
Value parameters 60
VAR block 13
Variable declaration 13
Variable parameters 61
Variables 13
Vectors and array notation 23
144 | Index