2 - Programming in AutoLISP
2 - Programming in AutoLISP
TRADE MARKS: All brand name and product names mentioned in this book are trade marks or registered trade mark of
their respective companies.
Every effort has been made to supply complete and accurate information. However, CEDTI assumes no responsibility for its
use, nor for any infringement of the intellectual property rights of third parties which would result from such use.
No part of this publication may be stored in a retrieval system, transmitted or reproduced in any forms or by any means,
electronic, photocopy, photograph, magnetic or otherwise, without written permission of CEDTI.
CEDTI/CFS/99/4/5.3/R1
FOREWORD
The Information Technology and Telecom sectors have suddenly opened up avenues, which require a very
large specially trained manpower. These sectors are highly dynamic and need training and re-training of manpower
at a rapid rate. The growing gap of requirement of the industry and its fulfilment has created a challenging situation
before manpower training institutes of the country. To meet this challenge most effectively, Centre for Electronics
Design and Technology of India (CEDTI) has launched its nation-wide franchising scheme.
Centre for Electronics Design and Technology of India (CEDTI) is an Autonomous Scientific Society under
the Govt. of India, Department of Electronics with its Headquarters at New Delhi. It operates seven centres located
at Aurangabad, Calicut, Gorakhpur, Imphal, Mohali, Jammu and Tezpur. The scheme will be implemented and
coordinated by these centres.
The scheme endeavours to promote high quality computer and information technology education in the
country at an affordable cost while ensuring uniform standards in order to build a national resource of trained
manpower. Low course fees will make this education available to people in relatively small, semi urban and rural
areas. State-of-the-art training will be provided keeping in view the existing and emerging needs of the industrial
and Govt. sectors. The examinations will be conducted by CEDTI and certificates will also be awarded by CEDTI.
The scheme will be operated through all the seven centres of CEDTI.
The CEDTI functions under the overall control and guidance of the Governing Council with Secretary,
Department of Electronics as its Chairman. The members of the council are drawn from scientific, government and
industrial sectors. The Centres have separate executive committees headed by Director General, CEDTI. The
members of these committees are from academic/professional institutes, state governments, industry and
department of electronics.
CEDTI is a quality conscious organisation and has taken steps to formally get recognition of the quality and
standards in various activities. CEDTI, Mohali was granted the prestigious ISO 9002 certificate in 1997. The other
centres have taken steps to obtain the certification as early as possible. This quality consciousness will assist
CEDTI in globalizing some of its activities. In keeping with its philosophy of ‘Quality in every Activity’, CEDTI will
endeavour to impart state of the art – computer and IT training through its franchising scheme.
The thrust of the Software Courses is to train the students at various levels to carry out the Management
Information System functions of a medium sized esTablishment, manufacture Software for domestic and export
use, make multimedia presentations for management and effectively produce various manufacturing and architectural
designs.
The thrust of the Hardware Courses at Technician and Telecommunication Equipment Maintenance Course
levels is to train the students to diagnose the faults and carry out repairs at card level in computers, instruments,
EPABX, Fax etc. and other office equipment. At Engineer and Network Engineer levels the thrust is to train them
as System Engineers to instal and supervise the Window NT, Netware and Unix Networking Systems and repair
Microcontrollers / Microprocessor based electronic applications.
An Advisory Committee comprising eminent and expert personalities from the Information Technology field
have been constituted to advise CEDTI on introduction of new courses and revising the syllabus of existing
courses to meet the changing IT needs of the trade, industry and service sectors. The ultimate objective is to
provide industry-specific quality education in modular form to supplement the formal education.
The study material has been prepared by the CEDTI, document centre. It is based on the vast and rich
instructional experience of all the CEDTI centres. Any suggestions on the improvement of the study material will
be most welcome.
(R. S. Khandpur)
Director General (CEDTI)
1. INTRODUCTION TO DATA TYPES AND
CONVENTIONS OF AutoLISP
1.1 INTEGER
An Integer is a whole number that does not contain a decimal point. AutoLISP integers
are 32 bit signed numbers with values ranging from + 2,147,483 to - 2,147. AutoLISP
uses 32 bit internally; those transferred between AutoLISP and AutoCAD are restricted
to 16 bit values and hence the user can pass integer values ranging from - 32,768 to +
32,767 only.
1.2 REAL
A real number is a number containing a decimal point (i.e., floating point numbers) and
can be either positive or negative. Real numbers are stored in double precision floating
point format, providing at least 14 significant digits of precision, even through the
AutoCAD command line areas shows only 6 significant digits.
1.3 STRING
A string is a group of characters enclosed within quoted strings. The backslash allows
control characters or escape code to be included within the string. Individual strings are
limited to 132 characters.
1.4 LIST
A list is a group of related values separated by spaces and enclosed within parenthesis.
List provides an efficient method of storing numerous related values.
1.5 SYMBOL
e.g.: a, xyz, a1, p1
File descriptors are alphanumeric labels assigned to files opened by AutoLISP. When an
AutoLISP function needs to write or read from a file the label of the must be referenced.
The following example opens the file text.dat for reading.
Command: (entlast)
<File name: 60000016>
Selection sets are groups of one or more objects. You can interactively add objects to or
more objects from selection sets, with AutoLISP routines.
Most of the AutoLISP functions are built-in subroutines called SUBRS. The functions
defined by external ADS and ARX applications are called EXTERNAL SUBRS. The
names of Subrs and External subrs are not case sensitive.
For example the “princ” function is a Subrs. The “acad_strlsort” function is External
subrs.
1.10 CONSTANTS
When you explicitly use a data type in an AutoLISP expression that value is known in a
constant. There is a predefined constant pi evaluating to 3.14159 and a symbol T
evaluating to “TRUE”. Constants should not be used as symbols. For example in the
following expression the symbol “a” is set to a constant value “CADD”.
Command: (setq a “CADD”)
AutoLISP code is usually stored in ASCII text files with a “.LSP” or “.MNL’ extension.
Although AutoLISP code can be entered at the command line, testing and debugging are
considerably easier when you load the AutoLISP code from a file rather than re-enter it
each time when you make a refinement.
• AutoLISP follows the prefix notation . i.e., the function name should precede the
arguments. e.g. (+ 4 5)
• Symbol names can consist of any sequence of printable characters except the
following:- (), `, “, ; and \
• Expressions can span multiple lines. Each expression beings with a left parenthesis
and consist of a function name and an optional list of arguments, each of which can
itself be an expression. The expression ends with a right parenthesis. e.g. (+ 2 3).
The arguments in form of expression lead to nesting of functions.
e.g. ( + 2 3 ), ( + A B), (+ 2 3) 4)
e.g. ( + 2 3 ), ( + 2 3) 7)
• Symbol and function names are not case sensitive, i.e., you may use upper or lower
case characters.
• Real numbers consist of one or more numeric digits, followed by a decimal point i.e.,
.4 is not recognized as a real; it should be entered as 0.4. Similarly 5. is not
recognized as real; it should be entered as 5.0. Integer values range between -
32,768 and +32,767.
• There should be a blank space between a function name and its arguments.
• Expressions nested within other expressions return their result to the surrounding
expressions. AutoLISP evaluates from the innermost expression and returns the
value to the surrounding expressions.
• Comments can be included in a program and they should begin with a semicolon “ ; ”
e.g. (seta 1 3)
Command: !a returns 3
Thee are four functions under this group. The arguments for these function can be
numbers, variables, symbols and constants. If any one argument is real then the result
will be a real value. If all the arguments are integers then the result will be an integer.
This function returns the sum of all numbers, which are real or integer. If all numbers are
integers then the result is an integer value. If any one number is a real number then the
result will be a real value.
e.g.
Command: (+ 5 3) returns 8
(+ 5. 7 9) returns 21.0
This function returns the result after subtracting <num2> from <num1>. If more than two
numbers are given as arguments then the result will be the sum of second and the
remaining arguments subtracted from <num1>. If only one argument is present then the
result will be the value of <num1> subtraced from 0.
e.g.
Command: (- 5 4) returns 1
(- 8 6 4) returns -2
(- 10 -5) returns 15
(- 3) returns -3
This function returns the product of all operands. If only one <num> is given then this
function returns the result of multiplying it by one and supplying no arguments returns
the result zero.
e.g.
Command: (* 5 4) returns 20
(* 1 2 3) returns 6
This function returns the quotient by dividing <num1> by <num>. If more than two
operands are given then <num1> will be divided by the product of others. If only one
<num> is given the function returns the result dividing it by one and supplying no
arguments returns zero.
e.g.
Command: (/ 5 4) returns 1
(/ 12 2 3) returns 2
There are three functions under this group. Using these basic. Trigonometric functions
you can evaluate any expressions involving Trigonometric calculations.
Sin
Syntax: (cos<angle>)
This function returns the sine value of the <angle> as a real value. The <angle.
argument must be expressed in RADIANS.
e.g.
Command: (sin 0) returns 1.0
Cos
This function returns the cosine value of <angle> as a real value. The <angle> argument
must be expressed in RADIANS.
e.g.
Command: (cos 0) returns 1.0
The result is tan inverse of <num1>. If both <num1> and <num2> are supplied then this
function returns the arctangent of <num1> divided by <num2> in RADIANS.
e.g.
3. BASIC STRUCTURE FUNCTIONS
abs
e.g.
Command: (abs -4) returns 4
e.g.
Command: (sqrt 16) returns 4.0
log
This function returns the natural logarithm of <number> to base e as a real. The
<number> should be positive.
e.g.
Command: (log 1) returns 0.0
(log 2.71828) returns 0.999999
exp
This function returns the value of the e raised to the specified number (the antilogarithm
of <number>).
e.g.
Command: (exp 0) returns 1.0
expt
This function returns the value of <base> raised to the specified <power>. The
arguments may be integer to real.
e.g.
Command: (expt 2 2 ) returns 4
max
e.g.
Command: (expt 4 5 3) returns 5
min
This function returns the minimum numeric value in the given set of arguments. The
arguments may be signed real or integers.
e.g.
(min -2 1.2 -0.5) returns -2.0
car
This function returns the element of the <list>. If the list is empty then the function
returns nil.
e.g.
Command: (setq L1 (list 2 “A” 32 “B”)) returns (2 “A” 32 “B”)
This function returns a list which contains all the elements of <list>, except the element
of the list.
e.g.
Command: (setq L (list 1 2 3 4) ) returns (1 2 3 4)
(cdr L) returns (2 3 4) )
(list 5 6) ) ) returns (1 2 3) (5 6)
(cdr m) returns ( (2 3 4) (5 6) )
The car and cdr functions can be concatenated up to FOUR levels. A few concentrations
are as shown below:-
e.g.
Command: (setq L (list 1 2 3 ) ) returns (1 2 3)
(cadr L) returns 2
(caddr L) returns 3
Explanation:
(cadr L) returns (2 3)
length
e.g.
Command: (setq L (list 1 2 “A” ) ) returns (1 2 “A”)
(length L) returns 3
(length m) returns 2
last
This function returns the last element of <list>. The <list> must not be nil.
e.g.
Command: (setq L (list 1 2 “A” ) ) returns (1 2 “A”)
nth
This function returns the indexed element of the <list>. The element of the <list> will
always have an index 0. The second element has an index 1, the third element has an
index 2 ans so on.
e.g.
(nth 0 L) returns 1
(nth 1 L) returns 2
reverse
e.g.
(reverse L) returns (4 3 2 1)
member
Syntax: (member <item> <list>
This scans through the <list> for the occurrence of the <item> and returns the remaining
portion of the list starting from the first occurrence of the <item>. The function returns
NIL, if the <item> is not found in the <list>.
e.g.
(reverse L) returns (4 3 2 1)
member
This scans through the <list> for the occurrence of the <item> and returns the remaining
portion of the list starting from the first occurrence of the <item>. The function returns
NIL, if the <item> is not found in the <list>.
e.g.
append
This function combines all the given arguments and forms a single list in the given order.
e.g.
subst
This function substitutes a <newitem> in the place of the <olditem> in the list and returns
the modified list. If the <olditem> does not exist in the given list then the original list is
returned.
e.g.
(subst `0 `1 a) returns (0 1 2 (3 4) 0)
acad_strlsort
This function sorts a <list> of string by alphabetical order. This will be useful when the
user presents a list containing Layers, Blocks or File names in a scrolling list box or
popup list within a dialog box.
e.g.
will return
6. PROGRAM CONTROL FUNCTIONS
This function checks for equality and returns T if all <atom>s are numerically equal and
NIL otherwise. The arguments can be either a number or a string.
e.g.
/=
This function checks for inequality and returns T if all the specified <atom>s are not
numerically equal and NIL otherwise.
e.g.
This function checks and returns T if <atom1> is less than <atom2> and NIL otherwise. If
more than two <atom>s are given then T is returned, if each <atom> is LESS THAN the
<atom> to its right and nil otherwise.
e.g.
<=
Syntax: (<=atom1> <atom2> [<atom3>...])
This checks and returns T if <atom1> is less than or equal to <atom2> and nil otherwise.
If more than two <atom>s are given then T is returned, if each <atom> is LESS THAN or
EQUAL TO the <atom> to its right.
(< = 2 3 4 4) returns T
>
This checks and returns T if <atom1> is greater than or equal to <atom2> and nill
otherwise. If more than two <atom>s are given then T is returned, if each <atom> is
GREATER THAN or EQUAL TO the <atom> to its right.
>=
This checks and returns T if <atom1> is greater than or equal to <atom2> and nil
otherwise. If more than two <atom>s are given then T is returned, if each <atom> is
GREATER THAN or EQUAL TO the <atom> to its right.
(> = 5 4 3 2) returns T
eq
This function returns, T if the two expressions given are identical. Otherwise it returns
NIL. This function determines whether <expr1> and <expr2> are bound to the same
object.
e.g.
This returns nil because a and c are not the same lists.
equal
This function returns T, if the two expressions evaluate to the same value. This is not the
same as eq function. the optional parameter <fuzz> denotes the maximum amount by
which the <expr1> and <expr2> can differ and still be considered equal.
e.g.
(equal a b) returns T
e.g.
(setq b 5.34678106)
minusp
This function returns, T if the specified <item> is negative and otherwise it returns NIL.
e.g.
(minusp -3,4) returns T
boundp
This function returns T, if the specified <item> is bound to a symbol and returns NIL if no
value is bound to the <item>. If the <item> is an undefined symbol then it is
automatically created and is bound to NIL.
e.g.
zerop
This function returns T, if the specified <item> is real or integer and evaluated to zero.
Otherwise it returns NIL.
e.g.
Command: (setq a 0 b 1)
(zerop a) returns T
This function returns T, if the specified <item> is a list. Otherwise it returns NIL.
e.g.
Command: (setq a `( (2 3) 4 5) )
(listp a) returns T
This function checks the data type of the specified <item>. The allowed data types are:
TYPE DESCRIPTION
STR Strings
INT Integers
SYM Symbols
LIST Lists
This function returns T if all the <expr>s evaluate to a non nil value. It returns NIL, if any
one of the given <expr>s evaluate to NIL and ceases further evaluation. You can also
supply variable names as <expr>s.
e.g.
(and a b) returns T
or
The function returns the value T, if any one or all the <expr>s in the argument list
evaluate to a non nil value. If all the <expr>s evaluate to nil then the function returns NIL.
Variable names can also be supplied as arguments.
e.g.
(or x y) returns T
7. STRING HANDLING FUNCTIONS
String is a group of characters enclosed within quotation marks. A single string value is
limited to 132 characters. Strings of unlimited length can be created by joining the strings
together and control characters can also be included within quoted strings. Applications
can also compare a string to a wild-card pattern and this facility is widely used when you
are building a selection set and retrieving the entirely data by application name.
strcase
This function converts the alphabetic characters of the <string> to upper or lower case,
depending on the optional argument <which>. When <which> is not specified or
evaluated to NIL, the <string> is converted to upper case. Otherwise it is converted to
lower case characters.
e.g.
This function combines multiple strings into a single string vlaue Blank and null strings
can also be combined.
e.g.
strlen
This function returns the number of characters in the specified <string>. Blank spaces
are also considered as valid characters.
e.g.
(strlen “cadd”) returns 5
(strlen “ “) returns 1
substr
This function returns the substring of a <string>. The <star> argument specifies the first
character of the string to be included the substring. The number of characters to be
included in the substring is specified by <length>. If <length> is not specified then the
function returns all characters including the following the specified <star> character.
e.g.
wcmatch
This function enables the application to compare a <string> to a wild-card pattern. If the
string matches with the pattern then this function returns T else NIL. The wild-card
patterns are similar to the regular expressions used by many application programs. The
<string> and the <match> can be either a quoted string or a variable. This function
compares the first 500 characters of the <string> and <match> specified.
The <match> can contain the wild-card matching characters shown in the following
table:
CHAR DEFINITION
. Matches any single non alphanumeric character
e.g.
read
This function returns the first atom or list in the specified <string>. The <string> cannot
contain blank spaces except within list or string.
e.g.
In the above case from the string “end of” only end is returned as, a blank space is
encountered after the first word.
8. CONVERSION FUNCTIONS
The functions convert data types and units. AutoLISP also provides functions to handle
decimal ASCII codes.
atof
e.g.
atoi
e.g.
itoa
This function returns the integer <item> given as arguemnt into a string.
e.g.
rtos
This function converts the specified <number> to a string according to the settings of
<mode> and <precision>. The <mode> and <precision> arguments must be integers.
MODE EDITING FORMAT
1. Scientific
2. Decimal
3. Engineering (feet and decimal inches)
4. Architectural (feet and fractional inches)
5. Fractional
The <precision> denotes the number of decimal places. When <mode> and <precision>
are not specified, the current strings of the AutoCAD system variables LUNITS and
LUPRECA are used.
e.g.
ascii
This function returns the ascii code of the first character of the <string>.
e.g.
angtos
This function is used to convert the specified <angle> to a string depending on the
settings of <mode> and <precision>. The arguments <mode> and <precision> must be
integer values. The following are the <mode> argument values:
0 Degrees
1 Degrees/minutes/seconds
2 Grads
3 Radians
4 Surveyor’s units
The <precision> denotes the number of decimal places. When <mode> and <precision>
are not specified, the current settings of the AutoCAD system variables AUNITS and
AUPREC are used.
e.g.
chr
This function returns the ASCII characters corresponding to the integer given as
argument. The value returned is a string.
e.g.
rem
This function divides <num1> by <num2>. If there are more than two arguments then the
remainder of FIRST and SECOND is divided by the THIRD and the value will be
returned.
e.g.
(rem 20 7 4) returns 2
fix
This function returns the truncated value of the <number> as an integer after discarding
the decimals. The arguments may be signed real or integer values.
e.g.
float
This function returns the conversion of the <number> into a real. the <number> may be
signed real or integer value.
e.g.
1+
This function returns the <number> increased by 1. The <number> may be a real or an
integer value.
e.g.
1-
This function returns the <number> increased by 1. The <number> may be a real or an
integer value.
e.g.
quote
1+
This function returns the <expr> as a symbol without evaluating it. The function can also
be represented by a “ ‘ “
e.g.
`(1 2) returns (1 2)
Adding Commands
If a function is defined with a name in the form C:XXX, it can be issued at the Command
prompt just like a built-in AutoCAD command. You can use this feature to add new
commands to AutoCAD or to redefine existing commands. To use the functions as
AutoCAD commands the function name must use the form C:XXX when XXX is the
function name which must be defined without arguments.
A function defined with C:XXX can also be invoked transparently preceded by a single
quote (`) from which any prompt of built-in AutoCAD command provided the function
does not call the command function.
for e.g.
Uisng the C:XXX feature you can define a command which displays a simple message.
Command: (defun C:Hello( ) prompt“Hello World”) (princ) )
returns
C: Hello
Hello is now defined as a command. To execute the command Hello, specify the
command name at the command prompt area as follows:
Command: Hello
When executed AtuoCAD displays the following message at the command prompt area.
Hello World
This command can be issued transparently because it does not call command function.
Command: LINE
From point: Hello
Hello World
From point:
e.g. 2
In the above function the “sp, L,w” are arguments and “sp1, sp2, sp3” are local variables
for the function. These variables lose their values after the function is executed.
AutoLISP allows you to define a list of symbols that are variable only to that function and
these are known as local symbols. The use of local symbols ensures that the variables
in your functions are unaffected by the surrounding application and that your variables
are not available after the function has completed the task.
The following example shows the use of local symbols in an user-defined function:
(princ)
Before you test this new function assign variables “a” and “b” to values other than
those used in the SAMPLE function.
Command: (Setq a 1 b 2)
You can verify that the variables “a” and “b” are actually set to those values by using the
exclamation point( ! ).
Command: !a
Command: !b
List
The list function combines a number of expressions into a list. This returns the
<expr>‘s as independent elements within parentheses. The elements can be of any type,
the number of elements are not limited and this function is frequently used to define a 2D
or 3D point variable (a list of two or three real).
e.g.
Command: (list 5 10.0) returns (5 10.0)
(setq A 2 B 5)
(list A B) returns (2 5)
(list (+ A 4) B) returns (6 5)
The list function may be a nested list, which contains lists as members.
e.g.
Command: (setq K (list 1 2 3) ) returns (1 2 3)
(setq L (list“C” “A” “D” “D”) returns (“C” “A” “D” “D”)
Polar
This function locates a 3D point with respect to the given <point> at a given <distance>
and <angle>. The <angle> must be specified in RADIANS. Though the <point> can be a
3D point, <angle> is always with respect to the current construction plane. The point is a
list of two real.
e.g.
The new point is fixed at an angle 0, at a distance of 3 units from the point 2,2.
angle
This function returns the angle between the two given points in RADIANS. The angle is
measured from X axis of current construction plane and if a 3D point is supplied then
they are project onto the current construction plane.
e.g.
Command: (angle `(2 2) `(3 3)) returns 0.785398
(corresponds to 45 degrees)
(corresponds to 90 degrees)
(corresponds of 0 degrees)
distance
This function returns the numeric distance between the two given points <pt1> and
<pt2>. The points can be list of a 2 or 3 real numbers or integers.
e.g.
FILE HANDLING
Every engineering design process, irrespective of the trade, whether Mechanical,
Civil or Architectural, needs data. These data are standards and thumb rules for an
optimum design solution. In conventional design process, an engineer has to repeatedly
refer volumes of catalogs, tables and charts which is a tedious process.
In the modern world, where computers are used to aid in the design process, one
need not look the design data table. All the necessary data can be stored as data files
and the design program can be made to open and read the files to locate the data.
Data files in the present scenario are simple ASCII files generated either
manually or through some other means
AutoLISP provides powerful yet simple functions to search and access the data
files, read and write/append information on to the data file.
A file can be opened and read/modified anywhere in a program. When you open
a file, AutoLISP provides a pointer which has to be assigned to a variable for further
reference.
write-char getfiled
findfile
Returns:
If the file is found Path of file as a STRING
The FINDFILE function searches for the given file whose name is given as the
string argument in the AutoCAD library path. The file name should also include the
extension of the file. If the drive or directory prefix is given then the file is searched only
in the specified drive or directory.
Example:
“C:\\ACADR14\\shaft.lsp”
otherwise,
Nil
Open
Returns:
The filename argument is a string that specifies the name and extension of the
file to be opened. The mode argument is the read/write flag. It must be a string
containing a single lower case letter. The following table describes the valid mode
letters.
“r” Open for reading. If filename does not exit, open returns nil.
“w” Open for writing. If filename does not exit, a new files is created and
opened. If filename already exists, Its existing data is overwritten.
“a” Open for appending. If filename does not exit, a new file is created a new
file is created and opened. If filename already exists, it is opened and the
pointer is positioned at the end of the existing data, so new data you write
to the file is appended to the existing data.
Open function returns a file description to be used by the other I/O functions. The
file descriptor must be assigned to a symbol that uses the seta function as shown below.
All further reference to the file should be through the file descriptor.
Example
Assuming that the files named in the following examples do not exit,
<File: # 22712c6>
Command: (setq f(open “nosuch.fil” “r”))
nil
Command: (setq f (open “lofgile” “a”))
<File: # 22711d8>
Close
Returns
on success nil
The <file descriptor> argument is a file descriptor obtained from the open
function. After a close, the file descriptor is unchanged but is no longer valid. All files
opened in a program have to be closed before the program is terminated.
Example
The following code counts the number of lines in the file check.txt and sets the
variable no_lines equal to that number:
read – char
Returns the ASCII code of the character read from an open file or from keyboard.
Returns
on success nil
This function returns the decimal ASCII code representing the character read
from the keyboard input buffer or from an open file described by the <file descriptor>. If
there are no <file descriptor>s and characters in the keyboard input buffer, the function
waits for a keyboard input.
Example
write – char
Returns
This function writes a character to the screen or to an open file. The <num>
argument is a decimal ASCII code for the character specified by the <num>. If no <file
descriptor> is given then the character is written on the screen else the character will be
written to the specified file.
Example
The last example writes character A onto the open file whose <file descriptor> is
fp. In either case, WRITE – CHAR will echo the argument (65 in this case) at the
Command: prompt
read – line
Returns
on failure nil
This function returns the line read from the keyboard or from an open file. When
this function is repeated with the file descriptor then the function returns the next line of
the file.
Example
(read-line fp)
returns the next input line from the file, or returns nil if the end-of-file has been
reached.
write – line
Returns:
on success string omitting the quotes
Example
getfiled
Display the standard AutoCAD file dialog box, and returns that the name
Returns
The <title> argument specifies the dialog box label. The <default> arguments
specifies a default file name to use for the dialog box. It can be empty string also. The
<ext> argument specifies the default file name extension, used as a mask for the files
presented to the user in a scrolling list box. This function returns the name of the
selected by the user, or nil if no file was selected. The <flags> argument is an integer
value ( a bit-coded field), the meaning of the various bit values are:
Example:
If you choose a file from the dialog box and click on OK then AutoCAD returns
the selected lisp file name.
ENTITY HANDLING
entlast
Returns the name of the last non-deleted main object (entity) in the drawing.
(entlast)
The entity name of the last drawn entity.
The entlast function is frequently used to obtain the name of a new entity that has
just been added with the command function. The entity need not be on the screen or on
a thawed layer to be selected.
Example:
(setq e1 (entlast))
entnext
(entnext [<ename>])
Returns:
This function retrieves entity names sequentially. When the optional parameter
<ename> is not specified, the function returns the entity name of the first entity in
database, else it returns the name of the seceding entity specified by <ename>.
Example
(setq e1 (entnext))
entsel
Prompts the user to select a single object (entity) by specifying a point
(entsel [<prompt>])
Returns
entity found at point picked The Entity name and the point picked as a
list.
This function is used to select an entity by specifying a point. The function returns
a list containing entity name and the point selected. When the optional argument
<prompt> is specified, AutoCAD prints the string in the command prompt area and waits
for user input. When it is not specified, AutoCAD displays a default prompt Select
Object: in the command prompt are:
Example:
Assuming if there is an object passing through point 3,3
Command: (entsel “Pick entity:”)
Pick entity: 3,3
nentsel
Prompts the user to select an object (entity) by specifying a point, and provides access
to the definition data contained within a complex object.
(nentsel [<prompt>])
Returns
Entity found at point picked The Entity name and the point picked as a list
This function provides access to the entities contained inside a nested entity.
(such as POLYLINES and INSERTS) If the optional argument <prompt> is passed then
this function waits for user selection by issuing <prompt> or else a standard prompt
Select Object: will be issued. If the selected objet is not a nested entity (i.e. neither a
POLYLINE nor a BLOCK INSERT) then this function returns same information as
ENTSELF function. When a sub entity of a nested entity is selected, this function returns
a list containing 4 elements.
The first element of that list will be entity name of the selected subentity. The
second element will be the point of selection, third one will be a matrix called `Model to
World Transformation Matrix’ which specifies the location of the sub entity with respect
to the insertion point of the block. The fourth member of the above list will be entity name
of the block that contains the selected sub entity.
)
(<Entity name: ename2> Name of most deeply nested block containing
selected entity
entupd
Updates the screen image of an object (entity)
(entupd <ename>)
Returns
When a polyline vertex or block attribute is modified with entmod, the entire complex
entity is not updated on the screen. The entupd function can be used to cause a modified polyline
or block to be updated on the screen. This function can be called with the entity name of any part
of the polyline or block; it need not be the head entity. While entupd is intended for polylines and
blocks with attributes, it can be called for any entity. It always regenerates the entity on the
screen, including all subentities.
Example
Assuming that the first entity in the drawing is a polyline with spline fit data and
with several vertices, then
assoc 10 en)
en)
)
entmod
Modifies the definition data of an object (entity)
Entmod <elist>)
Returns
This function modifies the database of the entity specified by <elist>. The <elist>
is the associative list of the entity obtained by entget function.
Example
entdel
Deletes objects (entities) or undeletes previously deleted objects.
(entdel <ename>)
Returns
This function is used to delete an entity in the current drawing editor. When used
again, it undeletes the entity specified by <ename> in the current drawing editor. All
deleted entities are purged when the current drawing is exited.
Example
If `a’ is a valid entity name, deletes the entity and returns entity name
Command: (entdel a)
<Entity name: 21d0548>
Command: (entdel b)
Error: bad argument type
(ENTDEL B)
*Cancel*
entmake
Creates a new entity (graphical object) in the drawing
(entmake <elist>)
Returns
This function creates a new entity in the current drawing making use of the entity
list specified by <elist> as the definition data. If successful then this returns the definition
data and nil otherwise.
1. Entity type
3. Optional arguments
a. Color
b. Layer
c. Linetype
d. Extrusion direction
e. Elevation
f. Thickness
SELECTION SET
SSGET FILTERS
This function selects all the entities conforming to a specified filter list. The <filter
list> is an association list that is used as a check to select objects. Each sub-list in the
<filter list> contains the group code and the value to matched. The group codes that can
be used in a ssget “X” function are,
Code Meaning
0 Entity type
2 Block name of block references
6 Line type name
7 Text style name for text and attribute definitions
8 Layer name
38 Elevation (real)
39 Thickness (real)
62 color number (0 => “BYBLOCK”
256 = > “BYLAYER”)
66 Attributes – follow flag for block references
210 3D extrusion direction vector (list of three reals).
Example:
sslength
Returns an integer containing the number of objects (entities) in selection set
(sslength) <ss>)
Returns
The number is returned as a real if it is greater than 32, 767. Selection sets never
contain duplicate selections of the same entity.
Example
(setq sset (ssget “L”)) ;Places the last object in selection set
sset
(sslength sset)
ssdel
Deletes an object (entity) from a selection set
(ssdel < ename > selection set name
on failure error message
This is used to delete the entity specified by < ename > from the selection set
<ss>. It returns the new selection set. If the entity is not found in the <ss>, the function
returns nil.
Example
(setq sd (ssget “X” (list (cons 0 :line”))); place all lines in the selection
; set sd.
sssetfirst
Sets which objects are selected and gripped
Returns
Example
ssgetfirst
Determines which objects are selected and gripped
(ssgetfirst
Returns
Example
Command: (ssgetfirst)
[<Selection set: 2> nil)
APPLICATION HANDLING
Almost all environments and software provide the user the tools to develop applications
for his/her need through customization. It is appropriate because it is very difficult or rather
impractical to group all the needs of the user by software developer himself. In this context,
understanding the importance and the advantages of customization, Autodesk has developed
AutoCAD with an open architecture, which encourages customizing to a large extent.
Autodesk has considered both the noise and experienced user has given tools for various
levels of customization. It depends on the knowledge and experience of the user, in AutoCAD as
well as other programming language such as AutoLISP and C. It is also based on the nature and
complexity of the application to the developed.
In order to utilize the function defined in these customized applications inside AutoCAD,
AutoLISP provides functions to load them. And the objective of this chapter is to enable you to
use those functions to load, unload and execute them.
xload
Loads an ADS application
(xload <adds application> [<on failure>])
This function load an <ads application>. If the application is successfully loaded then this
returns the application name or returns a standard error message otherwise. However, if the <on
failure> argument is supplied then the function returns the value of this argument upon failure
instead of an error message.
(arx)
Each ARX application loaded and its path is a quoted string in the list.
Example
Command: (arx)
(“acadapp.arx” “ geomal.arx” “oleaprof.arx”)
arxload
Loads an ARX application
(arxload <application> [<on failure>])
The <application> argument is entered as a quoted string or as a variable that contains the
name of an executable file. At the time the file is loaded, it is verified to be a valid ARX
application.
If the arxload operation fails then it normally causes an AutoLISP error. However, if the
<on failure> argument is supplied then arxload returns the value of this argument upon failure
instead of an error message. If the application is successfully loaded then the application name is
returned.
arxunload
Unloads an ARX <application> [<on failure>])
If the <application> is successfully unloaded then the <application> name is returned,
otherwise, an error message is issued.
Enter <application> as a quoted string or as a variable containing the name of an
application that was loaded with the arxload function. The <application> name must be entered
exactly as it was entered for the arxload function. If a path (directory name) or extension was
entered for the application in arxload, it can be omitted in the arxunload function.
autoload
autoxload
The <filename> argument is a string that specifies the ADS file that is loaded when one
of the commands defined by the <cmdlist> argument is entered at the command prompt. The
<cmdlist> argument must be a list of strings. The autoxload function returns nil.
The following code defines the C:APP1, C:APP3 and C:APP3 functions to load the
“bounsapp.lsp” file. The first time one of the command APP1, APP2 or APP3 are entered at the
command prompt the ARX application loads and the command continues.Example:
(autoxload “BOUNSAPP” (“APP1” “APP2” “APP3”))
AutoCAD gives you a language called as Dialog Control Language (DCL) which has got
its own syntax and functions, using which you could design your dialog box. Autodesk has
provided two file ACAD.DCL and BASE.DCL in which many of the commonly used dialog box
components, their structure and layout are predefined.
The definition a dialog box is written using Dialog Control Language in separate ASCII
files that contain the descriptions of the various elements of the dialog box. The above file should
have a file name extension .dcl. A .dcl file can contain the description of a single or multiple
dialogue boxes. The arrangement of elements (tiles) in a dialog box, such as buttons and
edit_boxes, is determined by their order in the .dcl file.
The following figure shows the various components of a Dialog box, In dialog box
creation these components are called as tiles.The two major components of a dialog box are tiles
and the box itself. The tiles can be arranged in any desired format (lime rows or columns). The
basic tiles, such as buttons, lists, edit boxes, images, toggle, radio button, etc., are predefined by
the programmable dialog box facility of AutoCAD and are defined in BASE.DCL. By grouping
the tiles into rows and columns, it is possible to create complex tiles, called subassembly. The
layout of the tile and their functionality are controlled by the attributes associated with the tiles.
alignment
alignment = position;
Applied to: all tiles
Specifies the justification of a tile within its cluster. The possible values of a tile inside a
column are left, right or centered (default : left), the possible values of a tile inside a row are top,
bottom, or centered (default : centered).
aspects_ratio
aspect_ratio = real;
Specifies the ratio of the width of the image to its height (width divided by height).
Possible values are floating-point values (default : none).
Color
Color = colorname;
Specifies the background (fill) color of the image. Possible values are an integer or
reserved word (default : 7) specified as an AutoCAD color number or as one of the symbolic
names show in the following table.
graphics_background Current background of the AutoCAD graphics screen
edit_limit
edit_limit = integer;
is_default
Specifies whether the button is the default selected (“pushed”) when the user presses the
accept (enter) key. Only one button in a dialog box can have the is_default attribute set to true.
is_enabled
Specifies whether the tile is initially grayed out (unavailable). Possible values are true of
false (default: true). If false, the tile is initially grayed out.
is_tab_stop
Specifies whether the tile receives keyboard focus when the user moves between tiles by
pressing the TAB key. If the tile is disabled, it isn’t tab stop even if this attribute is true. If false,
the tile is not a tab stop.
key
key = “string” ;
Specifies an ASCII name that the program uses to refer to this specific tile. Possible value
is a quoted string (no default). Within a particular dialog box, each key value must be unique.
This string is case sensitive: if you specify the key as Check_no BigTile, you cannot reference it
as check_no. Because the value of a key isn’t visible to the user, its name can be whatever you
choose (as long as it is unique to the dialog box).
label
label = “string”;
Specifies the text displayed within the tile. Possible value is a quoted string (default: a
blank string, “ “ . The placement of label text is tile specific.
If a character in the label string is preceded by an ampersand (&), that character becomes
the mnemonic.
list
list = “string”;
Specifies the initial set of lines (choices) to be placed in the popup_list or list_box.
Possible value is a quoted string (no default). Lines are separated by a new line symbol (\n). Tab
character (\t) can occur within each line.
mnemonic
mnemonic = “char”;
Specifies a keyboard mnemonic character for the tile. The mnemonic is underlined in the
tile’s label. Possible value is quoted string of a single character (no default). The character must
be one of the letters in the tile’s label. The character doesn’t have to be unique to the dialog box:
if more than one tile has the same mnemonic, the user presses that key to cycle through the tiles
sequentially.
value
value = “string“ ;
Applied to: text, active tiles (except buttons and image buttons)
Specifies the initial value of a tile. Possible value is a quoted string. The meaning of a
tile’s value varies depending on the kind of tile. The value of a tile can change at run time, with
user input or set_tile calls.
The value attribute of a tile is not considered when the dialog box is laid out. After the
layout is finished and the dialog box has been displayed, new_dialog uses the value attributes to
initialize each tile in the dialog box. At tile’s value attribute has no effect on the size or spacing of
tiles in the dialog box.
width
width = number;
Specifies the width of a tile. Possible values are an integer or a real number representing
the distance in character-width units. Do not specify this value unless the assigned defaults don’t
provide acceptable appearance. You must specify, however, the width of image tiles and image
buttons.
big_increment
big_increment = integer;
Specifies the value used by the slider’s incremental controls. The default value of
big_increment is one-tenth of the total range. The value must be within the range specified by
min_value and max_value.
small_increment
small_increment = integer;
Specifies the value by the slider’s incremental controls. Default value of small_increment
is one one-hundredth the total range. The value must be within the range specified by min_value
and max_value. This attribute is optional.
layout
layout = position;
Specifies the orientation of a slider. Possible values are horizontal or vertical (default:
horizontal). For horizontal sliders, the value increases from left to right. For vertical sliders, it
increases from button to top.
Password_char
Password_char = “cahr”;
Having seen the attributes which control the properties of the tiles, let us now have a
detailed look at the various Tiles available and how to use them,
dialog
: dialog {
initial_focus label value
}
A dialog is the tile that defines the dialog box. You should not specify both a label and value
attribute: the value attributes that of the label.
initial_focus :Specifies the key of the tile that receives the initial keyboard
focus.
initial_focus :Specifies the key of the tile that receives the initial keyboard
focus.
Example:
A button tile resembles a push button. The button’s label specifies text that appears inside
the button.
Dialog boxes must include an OK button (or its equivalent) for the user to press after
using (or reading) the box. Many dialog boxes also include a Cancel button that enables
the user to leave the dialog box without making any changes.
Example
:button {
label = “Execute”;
fixed_height = true;
fixed_width = true;
edit box
:edit_box{
alignment edit_limit edit_width fixed_height fixed_width height is_enabled
is_tab_stop key label mnemonic value width password_char.
An edit box is a field that enables the user to enter or edit a single line of text. An
optional label can appear to the left of the box. If the entered text is longer than
the length of the edit box, its scrolls horizontally.
Image
:image {
alignment aspect_ratio color fixed_height fixed_width height is_enabled
is_tab_stop key label mnemonic value width
}
An image is a rectangle in which a vector graphic picture is displayed. You can use an
image to display a vector, to fill an area with a color patch, or to display a slide image.
Example:
: image {
width = 5;
height = 5;
key = “til”;
}
list_box
:list_box{
alignment fixed_height fixed_width height is_enabled is_tab_stop key label list
mnemonic value width
Example:
: list_box
height = 10;
width = 10;
key = “lis”;
}
popup_list
:popup_list {
radio_button
: radio_button {
alignment fixed_height fixed_width height is_enabled is_tab_stop key label
mnemonic value width
Value: A quoted string (no default). If the value is “1”, the radio_button is on; if it is
“0”, the radio_buttons is off.
Example:
:radio_button {
label = “Left”;
mnemonic = “L”;
key = “left”;
}
text
text {
alignment fixed-height fixed_width height key label value width
Value :
If the string is “0”, the toggle box is blank (without a check mark).
slider
:slider {
action alignment big_increment fixed_height fixed_width height key label layout
max_value min_value mnemonic small_increment value width
ok_only
ok_only;
The ok_only tile is solitary OK button, such as the kind that alert boxes use. The
key of the OK button is “accept”.
ok_cancel;
The ok_cancel tile is a combination of the OK and Cancel buttons, and is the standard
combination for dialog boxes that can originate changes to data. The key of the Cancel
button is “cancel”.
errtile
errtile;
An error tile is a text tile that appears at the bottom of a dialog box. By default it’s blank,
put programs can display messages in it by setting the value of the tile whose key is “error”.
column
:column {
alignment fixed_height fixed_width height label width
}
Tiles in a column are laid out vertically in the order in which they appear in the DCL file.
A column can contain any kind of tile (except for solitary radio buttons), including rows
and other columns.
A column without a box has no additional attributes beyond the standard layout
attributes.
boxed_column
:boxed_column {
alignment fixed_height fixed_width height label width
}
A boxed column is box like rectangular area with a border around it. All the tiles that is
laid inside will be in a column fashion. If a boxed_column has a label, the label (title) is
embedden in it on the top left corner of the box.
boxed_radio_column
:bosed_radio_column {
alignment fixed_height fixed_width height label width
}
radio_column
:radio_column {
alignment fixed_height fixed_width height width
}
row
: row {
alignment fixed_height fixed_width height label width
}
A row is like a column, but its tiles are laid out horizontally instead of vertically, in the
order in which appear in the DCL file.
A row without a box has no additional attributes beyond the standard layout attributes.
boxed_row
:boxed_radio_row {
alignment fixed_height fixed_width height label width
}
A boxed row has a border around it. If a boxed row has a label, the label appears
embedded in it.
boxed_radio_row
:boxed_radio_rwo {
alignment fixed_height fixed_width height label width
}
A boxed radio row has a border around it. You treat the label the same way that you
would treat the label of a boxed row.
At any point of time only one radio_button can be selected indicating the option needed.
radio_row
:boxed_radio_row{
alignment fixed_height fixed_width height label width
}
SAMPLE PROGRAMS
This section gives you some sample DCL files. Try these first before creating any
Dialogs of your own on the exercises, and clearly understand each and every line in these
programs. Follow the instructions given.
Example: 01
/* this is a comment. . . .
The dialog name is mydial, and the coding is written in great.dcl. . .
*/
mydial:dialog {
load_dialog
(load_dialog <dcl_file>
The dcl_file argument is a string that specifies the .dcl file to load. Returns a positive
integer value (dcl_id) if successful, and returns a negative integer if it can’t open the file.
The dcl_id is used as a handle in subsequent new_dialog and unload_dialog calls.
Example:
new_dialog
The glgname argument is a string that specifies the dialog box, and dcl_id identifies the
.dcl file (you must have obtained its value from the load_dialog call).
Example:
FILE HANDLING
Every engineering design process, irrespective of the trade, whether Mechanical, Civil or
Architectural, needs data. These data are standards and thumb rules for an optimum design
solution. In conventional design process, an engineer has to repeatedly refer volumes of
catalogs, tables and charts which is a tedious process.
In the modern world, where computers are used to aid in the design process, one need
not look the design data table. All the necessary data can be stored as data files and the design
program can be made to open and read the files to locate the data.
Data files in the present scenario are simple ASCII files generated either manually or
through some other means
AutoLISP provides powerful yet simple functions to search and access the data files,
read and write/append information on to the data file.
A file can be opened and read/modified anywhere in a program. When you open a file,
AutoLISP provides a pointer which has to be assigned to a variable for further reference.
write-char getfiled
findfile
Returns:
The FINDFILE function searches for the given file whose name is given as the string
argument in the AutoCAD library path. The file name should also include the extension of the
file. If the drive or directory prefix is given then the file is searched only in the specified drive or
directory.
Example:
“C:\\ACADR14\\shaft.lsp”
otherwise,
Nil
Open
Returns:
The filename argument is a string that specifies the name and extension of the file to be
opened. The mode argument is the read/write flag. It must be a string containing a single lower
case letter. The following table describes the valid mode letters.
“r” Open for reading. If filename does not exit, open returns nil.
“w” Open for writing. If filename does not exit, a new files is created and opened. If
filename already exists, Its existing data is overwritten.
“a” Open for appending. If filename does not exit, a new file is created a new file is
created and opened. If filename already exists, it is opened and the pointer is
positioned at the end of the existing data, so new data you write to the file is
appended to the existing data.
Open function returns a file description to be used by the other I/O functions. The file
descriptor must be assigned to a symbol that uses the seta function as shown below. All further
reference to the file should be through the file descriptor.
Example
Assuming that the files named in the following examples do not exit,
<File: # 22712c6>
Command: (setq f(open “nosuch.fil” “r”))
nil
Command: (setq f (open “lofgile” “a”))
<File: # 22711d8>
Close
Returns
on success nil
The <file descriptor> argument is a file descriptor obtained from the open function. After
a close, the file descriptor is unchanged but is no longer valid. All files opened in a program
have to be closed before the program is terminated.
Example
The following code counts the number of lines in the file check.txt and sets the variable
no_lines equal to that number:
read – char
Returns the ASCII code of the character read from an open file or from keyboard.
Returns
on success nil
on failure error message
This function returns the decimal ASCII code representing the character read from the
keyboard input buffer or from an open file described by the <file descriptor>. If there are no <file
descriptor>s and characters in the keyboard input buffer, the function waits for a keyboard input.
Example
write – char
Returns
This function writes a character to the screen or to an open file. The <num> argument is
a decimal ASCII code for the character specified by the <num>. If no <file descriptor> is given
then the character is written on the screen else the character will be written to the specified file.
Example
The last example writes character A onto the open file whose <file descriptor> is fp. In
either case, WRITE – CHAR will echo the argument (65 in this case) at the Command: prompt
read – line
Returns
on success line read as string
on failure nil
This function returns the line read from the keyboard or from an open file. When this
function is repeated with the file descriptor then the function returns the next line of the file.
Example
(read-line fp)
returns the next input line from the file, or returns nil if the end-of-file has been reached.
write – line
Returns:
on success string omitting the quotes
Example
getfiled
Display the standard AutoCAD file dialog box, and returns that the name
Returns
The <title> argument specifies the dialog box label. The <default> arguments specifies a
default file name to use for the dialog box. It can be empty string also. The <ext> argument
specifies the default file name extension, used as a mask for the files presented to the user in a
scrolling list box. This function returns the name of the selected by the user, or nil if no file was
selected. The <flags> argument is an integer value ( a bit-coded field), the meaning of the
various bit values are:
Example:
If you choose a file from the dialog box and click on OK then AutoCAD returns the
selected lisp file name.
entlast
Returns the name of the last non-deleted main object (entity) in the drawing.
(entlast)
The entlast function is frequently used to obtain the name of a new entity that has just
been added with the command function. The entity need not be on the screen or on a thawed
layer to be selected.
Example:
(setq e1 (entlast))
entnext
(entnext [<ename>])
Returns:
if not found nil
This function retrieves entity names sequentially. When the optional parameter <ename>
is not specified, the function returns the entity name of the first entity in database, else it returns
the name of the seceding entity specified by <ename>.
Example
(setq e1 (entnext))
entsel
(entsel [<prompt>])
Returns
entity found at point picked The Entity name and the point picked as a list.
This function is used to select an entity by specifying a point. The function returns a list
containing entity name and the point selected. When the optional argument <prompt> is
specified, AutoCAD prints the string in the command prompt area and waits for user input.
When it is not specified, AutoCAD displays a default prompt Select Object: in the command
prompt are:
Example:
Assuming if there is an object passing through point 3,3
Command: (entsel “Pick entity:”)
Pick entity: 3,3
nentsel
Prompts the user to select an object (entity) by specifying a point, and provides access to the
definition data contained within a complex object.
(nentsel [<prompt>])
Returns
Entity found at point picked The Entity name and the point picked as a list
This function provides access to the entities contained inside a nested entity. (such as
POLYLINES and INSERTS) If the optional argument <prompt> is passed then this function
waits for user selection by issuing <prompt> or else a standard prompt Select Object: will be
issued. If the selected objet is not a nested entity (i.e. neither a POLYLINE nor a BLOCK
INSERT) then this function returns same information as ENTSELF function. When a sub entity
of a nested entity is selected, this function returns a list containing 4 elements.
The first element of that list will be entity name of the selected subentity. The second
element will be the point of selection, third one will be a matrix called `Model to World
Transformation Matrix’ which specifies the location of the sub entity with respect to the insertion
point of the block. The fourth member of the above list will be entity name of the block that
contains the selected sub entity.
If the selected entity is an ATTRIBUTE of an INSERT then this function returns only the
entity name of the attribute and the pick point.
entupd
(entupd <ename>)
Returns
When a polyline vertex or block attribute is modified with entmod, the entire complex entity is
not updated on the screen. The entupd function can be used to cause a modified polyline or block to be
updated on the screen. This function can be called with the entity name of any part of the polyline or
block; it need not be the head entity. While entupd is intended for polylines and blocks with attributes, it
can be called for any entity. It always regenerates the entity on the screen, including all subentities.
Example
Assuming that the first entity in the drawing is a polyline with spline fit data and with
several vertices, then
assoc 10 en)
en)
)
entmod
Entmod <elist>)
Returns
This function modifies the database of the entity specified by <elist>. The <elist> is the
associative list of the entity obtained by entget function.
Example
entdel
(entdel <ename>)
Returns
This function is used to delete an entity in the current drawing editor. When used again,
it undeletes the entity specified by <ename> in the current drawing editor. All deleted entities
are purged when the current drawing is exited.
Example
If `a’ is a valid entity name, deletes the entity and returns entity name
Command: (entdel a)
<Entity name: 21d0548>
Command: (entdel b)
Error: bad argument type
(ENTDEL B)
*Cancel*
entmake
(entmake <elist>)
Returns
This function creates a new entity in the current drawing making use of the entity list
specified by <elist> as the definition data. If successful then this returns the definition data and
nil otherwise.
The minimum data <elist> for making an entity are as follows:
1. Entity type
3. Optional arguments
a. Color
b. Layer
c. Linetype
d. Extrusion direction
e. Elevation
f. Thickness
SSGET FILTERS
This function selects all the entities conforming to a specified filter list. The <filter list> is
an association list that is used as a check to select objects. Each sub-list in the <filter list>
contains the group code and the value to matched. The group codes that can be used in a ssget
“X” function are,
Code Meaning
0 Entity type
2 Block name of block references
6 Line type name
7 Text style name for text and attribute definitions
8 Layer name
38 Elevation (real)
39 Thickness (real)
62 color number (0 => “BYBLOCK”
256 = > “BYLAYER”)
66 Attributes – follow flag for block references
210 3D extrusion direction vector (list of three reals).
Example:
(cons 8 “C”))) ;selects all lines in the layer named C
sslength
(sslength) <ss>)
Returns
The number is returned as a real if it is greater than 32, 767. Selection sets never
contain duplicate selections of the same entity.
Example
(setq sset (ssget “L”)) ;Places the last object in selection set sset
(sslength sset)
ssdel
This is used to delete the entity specified by < ename > from the selection set <ss>. It
returns the new selection set. If the entity is not found in the <ss>, the function returns nil.
Example
(setq sd (ssget “X” (list (cons 0 :line”))); place all lines in the selection
; set sd.
sssetfirst
Returns
Example
ssgetfirst
Returns
Example
Command: (ssgetfirst)
[<Selection set: 2> nil)
APPLICATION HANDLING
Almost all environments and software provide the user the tools to develop applications for
his/her need through customization. It is appropriate because it is very difficult or rather impractical to
group all the needs of the user by software developer himself. In this context, understanding the
importance and the advantages of customization, Autodesk has developed AutoCAD with an open
architecture, which encourages customizing to a large extent.
Autodesk has considered both the noise and experienced user has given tools for various levels
of customization. It depends on the knowledge and experience of the user, in AutoCAD as well as other
programming language such as AutoLISP and C. It is also based on the nature and complexity of the
application to the developed.
AutoCAD can be customized through,
¾ AutoLISP, a programming language framed by the Autodesk for developing small applications
involving either designing or drafting in AutoCAD.
¾ ADS – AutoCAD Development System, a programming language using the structure of `C’
language.
In order to utilize the function defined in these customized applications inside AutoCAD,
AutoLISP provides functions to load them. And the objective of this chapter is to enable you to use those
functions to load, unload and execute them.
xload
This function load an <ads application>. If the application is successfully loaded then this returns
the application name or returns a standard error message otherwise. However, if the <on failure>
argument is supplied then the function returns the value of this argument upon failure instead of an error
message.
This function fails to load if the application is already loaded.
Example
xunload
This function unloads an <ADS application> specified. If the application is successfully unloaded
then it returns the application name else returns an error message. The <application name> should be
entered as it was entered during xload. The directory name can be omitted for this function. If the xunload
application fails it causes an AutoLISP error. However if the <on failure> argument is supplied the
functions the value of this argument <on failure> argument is supplied then the function returns the value
of this argument <on failure> instead of issuing an error message.
Example:
ads
(ads)
Each ADS application loaded and its path is a quoted string in the list.
arx
(arx)
Each ARX application loaded and its path is a quoted string in the list.
Example
Command: (arx)
arxload
The <application> argument is entered as a quoted string or as a variable that contains the name
of an executable file. At the time the file is loaded, it is verified to be a valid ARX application.
If the arxload operation fails then it normally causes an AutoLISP error. However, if the <on
failure> argument is supplied then arxload returns the value of this argument upon failure instead of an
error message. If the application is successfully loaded then the application name is returned.
arxunload
If the <application> is successfully unloaded then the <application> name is returned, otherwise,
an error message is issued.
Enter <application> as a quoted string or as a variable containing the name of an application that
was loaded with the arxload function. The <application> name must be entered exactly as it was entered
for the arxload function. If a path (directory name) or extension was entered for the application in arxload,
it can be omitted in the arxunload function.
autoload
The <filename> argument is a string that specifies the “.lsp” file that is loaded when one of the
command defined by the <cmdlist> argument is entered at the command prompt. The <cmdlist>
argument must be a list of strings. The autoload function returns nil.
The following code defines the C:APP1, C:APP2 and C:APP3 functions to load the
“bounsapp.lsp” file. The fist time one of the command APP1, APP2 or APP3 are entered at the command
prompt the ARX application loads and the command continues.
Example:
autoxload
The <filename> argument is a string that specifies the ADS file that is loaded when one of the
commands defined by the <cmdlist> argument is entered at the command prompt. The <cmdlist>
argument must be a list of strings. The autoxload function returns nil.
The following code defines the C:APP1, C:APP3 and C:APP3 functions to load the
“bounsapp.lsp” file. The first time one of the command APP1, APP2 or APP3 are entered at the command
prompt the ARX application loads and the command continues.
Example:
DIALOG CONTROL LANGUAGE [DCL]
AutoCAD gives you a language called as Dialog Control Language (DCL) which has got its own
syntax and functions, using which you could design your dialog box. Autodesk has provided two file
ACAD.DCL and BASE.DCL in which many of the commonly used dialog box components, their
structure and layout are predefined.
The definition a dialog box is written using Dialog Control Language in separate ASCII files that
contain the descriptions of the various elements of the dialog box. The above file should have a file name
extension .dcl. A .dcl file can contain the description of a single or multiple dialogue boxes. The
arrangement of elements (tiles) in a dialog box, such as buttons and edit_boxes, is determined by their
order in the .dcl file.
The following figure shows the various components of a Dialog box, In dialog box creation these
components are called as tiles.
The two major components of a dialog box are tiles and the box itself. The tiles can be arranged in any
desired format (lime rows or columns). The basic tiles, such as buttons, lists, edit boxes, images, toggle,
radio button, etc., are predefined by the programmable dialog box facility of AutoCAD and are defined in
BASE.DCL. By grouping the tiles into rows and columns, it is possible to create complex tiles, called
subassembly. The layout of the tile and their functionality are controlled by the attributes associated with
the tiles.
alignment
alignment = positive;
Applied to: all tiles
Specifies the justification of a tile within its cluster. The possible values of a tile inside a column
are left, right or centered (default : left), the possible values of a tile inside a row are top, bottom, or
centered (default : centered).
aspects_ratio
aspect_ratio = real;
Specifies the ratio of the width of the image to its height (width divided by height). Possible
values are floating-point values (default : none).
Color
Color = colorname;
Specifies the background (fill) color of the image. Possible values are an integer or reserved word
(default : 7) specified as an AutoCAD color number or as one of the symbolic names show in the
following table.
Dialog_foreground Current dialog box foreground color (for text)
edit_limit
edit_limit = integer;
Specifies the maximum no of characters a user is allowed to enter in the edit_box. Possible values
in an integer (default : 132). The maximum edit_limit allowed is 256 characters.
is_default
is_default = true – false;
Specifies whether the button is the default selected (“pushed”) when the user presses the accept
(enter) key. Only one button in a dialog box can have the is_default attribute set to true.
is_enabled
Specifies whether the tile is initially grayed out (unavailable). Possible values are true of false
(default: true). If false, the tile is initially grayed out.
is_tab_stop
Specifies whether the tile receives keyboard focus when the user moves between tiles by pressing
the TAB key. If the tile is disabled, it isn’t tab stop even if this attribute is true. If false, the tile is not a tab
stop.
key
key = “string” ;
Specifies an ASCII name that the program uses to refer to this specific tile. Possible value is a
quoted string (no default). Within a particular dialog box, each key value must be unique. This string is
case sensitive: if you specify the key as Check_no BigTile, you cannot reference it as check_no. Because
the value of a key isn’t visible to the user, its name can be whatever you choose (as long as it is unique to
the dialog box).
label
label = “string”;
Specifies the text displayed within the tile. Possible value is a quoted string (default: a blank
string, “ “ . The placement of label text is tile specific.
If a character in the label string is preceded by an ampersand (&), that character becomes the
mnemonic.
list
list = “string”;
Specifies the initial set of lines (choices) to be placed in the popup_list or list_box. Possible value
is a quoted string (no default). Lines are separated by a new line symbol (\n). Tab character (\t) can occur
within each line.
mnemonic
mnemonic = “char”;
Specifies a keyboard mnemonic character for the tile. The mnemonic is underlined in the tile’s
label. Possible value is quoted string of a single character (no default). The character must be one of the
letters in the tile’s label. The character doesn’t have to be unique to the dialog box: if more than one tile
has the same mnemonic, the user presses that key to cycle through the tiles sequentially.
value
value = “string“ ;
Applied to: text, active tiles (except buttons and image buttons)
Specifies the initial value of a tile. Possible value is a quoted string. The meaning of a tile’s value
varies depending on the kind of tile. The value of a tile can change at run time, with user input or set_tile
calls.
The value attribute of a tile is not considered when the dialog box is laid out. After the layout is
finished and the dialog box has been displayed, new_dialog uses the value attributes to initialize each tile
in the dialog box. At tile’s value attribute has no effect on the size or spacing of tiles in the dialog box.
width
width = number;
Specifies the width of a tile. Possible values are an integer or a real number representing the
distance in character-width units. Do not specify this value unless the assigned defaults don’t provide
acceptable appearance. You must specify, however, the width of image tiles and image buttons.
big_increment
big_increment = integer;
Specifies the value used by the slider’s incremental controls. The default value of big_increment
is one-tenth of the total range. The value must be within the range specified by min_value and max_value.
small_increment
small_increment = integer;
Applied to: slider
Specifies the value by the slider’s incremental controls. Default value of small_increment is one
one-hundredth the total range. The value must be within the range specified by min_value and
max_value. This attribute is optional.
layout
layout = position;
Specifies the orientation of a slider. Possible values are horizontal or vertical (default: horizontal).
For horizontal sliders, the value increases from left to right. For vertical sliders, it increases from button to
top.
Password_char
Password_char = “cahr”;
Specifies the character to be used as the password character. If password_char is specified and is
not null, that character is displayed in the edit box instead of the characters entered by the user. The use of
this attribute has no effect on the retrieval of the value entered by the user. It alters only the display of the
characters in the edit box Having seen the attributes which control the properties of the tiles, let us
now have a detailed look at the various Tiles available and how to use them,
dialog
: dialog {
initial_focus label value
}
A dialog is the tile that defines the dialog box. You should not specify both a label and value attribute: the
value attributes that of the label.
initial_focus :Specifies the key of the tile that receives the initial keyboard focus.
initial_focus :Specifies the key of the tile that receives the initial keyboard focus.
Example:
:button {
alignment fixed_height fixed_width height is_cancel is_default is_enabled is_tab_stop key label
mnemonic width
A button tile resembles a push button. The button’s label specifies text that appears inside the
button.
Dialog boxes must include an OK button (or its equivalent) for the user to press after using (or
reading) the box. Many dialog boxes also include a Cancel button that enables the user to leave
the dialog box without making any changes.
Example
:button {
label = “Execute”;
fixed_height = true;
fixed_width = true;
edit box
:edit_box{
alignment edit_limit edit_width fixed_height fixed_width height is_enabled is_tab_stop
key label mnemonic value width password_char.
An edit box is a field that enables the user to enter or edit a single line of text. An
optional label can appear to the left of the box. If the entered text is longer than the length
of the edit box, its scrolls horizontally.
Image
:image {
alignment aspect_ratio color fixed_height fixed_width height is_enabled is_tab_stop key
label mnemonic value width
An image is a rectangle in which a vector graphic picture is displayed. You can use an image to
display a vector, to fill an area with a color patch, or to display a slide image.
Example:
: image {
width = 5;
height = 5;
key = “til”;
}
list_box
:list_box{
alignment fixed_height fixed_width height is_enabled is_tab_stop key label list
mnemonic value width
Example:
: list_box
height = 10;
width = 10;
key = “lis”;
}
popup_list
:popup_list {
radio_button
: radio_button {
alignment fixed_height fixed_width height is_enabled is_tab_stop key label mnemonic
value width
Value: A quoted string (no default). If the value is “1”, the radio_button is on; if it is “0”, the
radio_buttons is off.
Example:
:radio_button {
label = “Left”;
mnemonic = “L”;
key = “left”;
}
text
text {
alignment fixed-height fixed_width height key label value width
A text tile display a text string for titling or informational purposes.
toggle
: toggle {
alignment fixed_height fixed_width height key label value width
Value :
If the string is “0”, the toggle box is blank (without a check mark).
slider
:slider {
action alignment big_increment fixed_height fixed_width height key label layout
max_value min_value mnemonic small_increment value width
ok_only
ok_only;
The ok_only tile is solitary OK button, such as the kind that alert boxes use. The key of
the OK button is “accept”.
ok_cancel
ok_cancel;
The ok_cancel tile is a combination of the OK and Cancel buttons, and is the standard
combination for dialog boxes that can originate changes to data. The key of the Cancel button is
“cancel”.
errtile
errtile;
An error tile is a text tile that appears at the bottom of a dialog box. By default it’s blank, put
programs can display messages in it by setting the value of the tile whose key is “error”.
column
:column {
alignment fixed_height fixed_width height label width
}
Tiles in a column are laid out vertically in the order in which they appear in the DCL file. A
column can contain any kind of tile (except for solitary radio buttons), including rows and other
columns.
A column without a box has no additional attributes beyond the standard layout attributes.
boxed_column
:boxed_column {
alignment fixed_height fixed_width height label width
A boxed column is box like rectangular area with a border around it. All the tiles that is laid
inside will be in a column fashion. If a boxed_column has a label, the label (title) is embedden in
it on the top left corner of the box.
boxed_radio_column
:bosed_radio_column {
alignment fixed_height fixed_width height label width
}
A boxed_radio_column is very similar to the boxed_column in all means except one function. It
encloses the radio_buttons in a column, at a point of time only one radio button can be selected.
You treat the label the same way that you would treat the label of a boxed column.
radio_column
:radio_column {
alignment fixed_height fixed_width height width
}
row
: row {
alignment fixed_height fixed_width height label width
}
A row is like a column, but its tiles are laid out horizontally instead of vertically, in the order in
which appear in the DCL file.
A row without a box has no additional attributes beyond the standard layout attributes.
boxed_row
:boxed_radio_row {
boxed_radio_row
:boxed_radio_rwo {
A boxed radio row has a border around it. You treat the label the same way that you would treat
the label of a boxed row.
At any point of time only one radio_button can be selected indicating the option needed.
radio_row
:boxed_radio_row{
alignment fixed_height fixed_width height label width
}
SAMPLE PROGRAMS
This section gives you some sample DCL files. Try these first before creating any Dialogs of your
own on the exercises, and clearly understand each and every line in these programs. Follow the
instructions given.
Example: 01
/* this is a comment. . . .
*/
mydial:dialog {
load_dialog
(load_dialog <dcl_file>
The dcl_file argument is a string that specifies the .dcl file to load. Returns a positive integer
value (dcl_id) if successful, and returns a negative integer if it can’t open the file. The dcl_id is
used as a handle in subsequent new_dialog and unload_dialog calls.
Example:
new_dialog
The glgname argument is a string that specifies the dialog box, and dcl_id identifies the .dcl file
(you must have obtained its value from the load_dialog call).
Example:
Render Application Programming Interface
The application-programming interface (API) to AutoCAD Render is provided by an ADS application.
You can run AutoCAD Render commands from AutoLisp using (c: command) convention or through
ADS using ADS_invoke ().
The AutoCAD Render API commands have three different return values that calling application can use
to determine if the command is successful
1. IF the command fails, the function returns nil in AutoLisp or a NULL result buffer pointer in ADS
2. If the command is successful, and the command returns explicit values, it returns a value like .03
3. If the command is successful, and the command returns nonexplicit values, the function returns! (in
ADS , this is a single result buffer with a restyle of RTSHORT and resval.rint=1)
The setting of RMan Prompting does not affect the Render API
FINISH Command
The finish command lets you add a new surface finish, and modify, delete, import-export, or attach an
existing finish.
8 “L” List all finishes in the drawing or return a definition of the specified finish
SYNTAX: - (c: finish “L” name)
The FINISH command has following options
LIGHT Command
The LIGHT command lets you add a new light, and modify or delete an existing light.
7 “D” Delete existing light
SYNTEX: - (c: light “D” name )
9 “L” List all lights in the drawing or return a definition of the specified light
SYNTEX: - (c: light “L” name)
RCONFIG Command
The RCONFIG command reconfigures your current rendering setup. Use following syntax:
(c: rconfig )
RENDER Command
RENDSCR Command
(c: rendscr )
REPLAY Command
The REPLAY command lets you display RND, TGA, TIFF, or GIF files on the AutoCAD rendering
display
RPREF Command
When you use Render, the type of rendering AutoCAD produces depends on yours specified preferences.
The RPREF command lets you set these preferences
SAVEIMG Command
The SAVEIMG command lets you save any image in the framebuffer to a GIF, RND, TGA, or a TIFF file
(c: saveimg filename type [portion] [ xoff yoff xsize ysize ] [ compression ] )
OPTION DESCRIPTION DEFAULT
SCENE Command
A scene represents a particular view of any portion of the drawing including the whole drawing, together
with one or more lights . The SCENE command lets you create a new scene , or delete and modify an
existing scene .
6 “L” Lists all scenes in the drawing or return a definition of the specified scene
SYNTAX: - (c: scene “L” name )
STSTS Command
( c: stats [filename ] )
ASI Functions
The ASI library contains functions that access the database by converting SQL expression to standard
data structures that are transferred to the driver
ASI Functions
Internal Data
Host variables
ASI_HINT int
ASI_HREAL double
ASI_HSHORT short
ASI_HLONG long
ASI_HFLONT float
ASI_CHAR CHARACTER
ASI_NUMERIC NUMERIC
ASI_DECIMAL DECIMAL
ASI_INTEGER INTEGER
ASI_SMALLINT SMALLINT
ASI_FLOAT FLOAT
ASI_REAL REAL
Database Processing
1. Connecting to database
2. Opening a communication handle
3. Compiling the original SQL statement
4. Executing the SQL statement
5. Fetching. This step follows the query execution
6. Closing a communication handle
7. Disconnecting from database
HANDLES
All ASI function passes information to each other by using handle. A handle is an ASI defined data
structure used for passing data back and forth between the application and the driver. There are three
types of handle
1. Driver Handle
Use of Driver handle is points to the active DBMS
2. Database Handle
Use of Database handle is points to the active database
3. Communication Handle
Use of Communication handle is points to the active row
Function Synopsis
This section consists of a synopsis of library functions, grouped by topic. Each function is followed by a
brief description
Driver-based Functions
ASI_CFGDRV Configures a driver
ASI_TERMSQL Terminates the ASI interface
Processing Functions
ASI_ROWQTY Gets number of rows in the selection set
ASI and ASELQED support SQL syntax compatible with the ANSI X3.135-1989 SQL Standard. ASI is
also fully compatible with the ISO SQL Standard. A summary of SQL syntax and ASE SQL standards
follows. The SQL standard listed is not a complete listed is of the ANSI standard. Some commands are a
superset of the ANSI standard.
SYNTACTIC NOTATION
The acad_colordlg function returns the color number that the user selects via the OK button. If the user
cancels the dialogue box, acad_colordlg returns nil.
Display the standard AutoCAD Help dialogues box using a specified file. You can call this function from
your AutoLISP routine to provide help on a standard AutoCAD command or own application specific
help.
3. (acad_strlsort list)
Sort a list of strings by alphabetical order. The list argument is the list of string to be sorted. The
acad_strlsort function returns a list of the same string in alphabetical order.
These functions let you access ADS-defined AutoCAD commands from AutoLISP. They are available
only when the associated ADS program is loaded.
There are following functions in this sections
(align ss s1 d1 s2 d2 s3 d3 )
Uses the ALIGN command to perform a 3D move. If successful align returns T, otherwise it returns nil.
(bherrs)
Gets an error message generated by failed call to c: bhatch or c: bpoly. If successful, it sets the results
to contain the message string; otherwise, the result is nil.
The bherrs function is defined in acaddapp.exp.
calls the BHATCH command and performs a boundary hatch on the specified area. The c: bhatch
function is defined in acadapp.exp.
Calls the BPOLY command and creates a boundary Polyline. The c: bpoly function is defined in
acadapp.exp
Calls the PSDRAG command and sets the integer value mode. The mode argument is an integer that
equals either 0 or 1. The c: psdrag function is defined in acadapp.exp.
Fill a polyline with a postscript file. The ent argument is the name of polyline. The pattern argument is a
string containing the name of the fill pattern. The pattren string must be identical to the name of fill
pattern defined in current acad.psf file.
(c: psin filename position scale)
Invokes the PSIN command to import an encapsulated PostScript (. eps) file. The position argument is a
point specifying the insertion point of the PostScript block.
(mirror3d ss str pt xy )
Calls most REGION MODELER COMMANDS. Solxxx is name of a command; arg1 and arg2 are
ordinary AutoLISP expressions. The REGION MODELER supports the following commands in
AutoLISP.
ADS LIBRARY EXTENSIONS
Externally Defined AutoCAD Functions
These functions are standard AutoCAD facilities externally defined by the ADS program acadapp. They
are available only if acadapp is loaded, which it is by default. You can invoke them via ads_invoke (), as
described here.
The acad_colordlg function returns the color number that the user selects via the OK button. If the user
cancels the dialogue box, acad_colordlg returns nil.
Display the standard AutoCAD Help dialogues box using a specified file. You can call this function from
your AutoLISP routine to provide help on a standard AutoCAD command or own application specific
help.
3. (acad_strlsort list)
Sort a list of strings by alphabetical order. The list argument is the list of string to be sorted. The
acad_strlsort function returns a list of the same string in alphabetical order
Error Handling
Use the error( ) function (in file calerr.c) to indicate error conditions, as shown in the previous code
samples. An error () call has this format:
This function sets the global integer variable cal_err to the value of n, and display an error message. If
cal_err is already nonzero , the error () call has no effect. This avoids printing several error messages
caused by single error.
The “ERROR MESSAGE” string is used three ways, depending on the value of n:
2. If n is the number of an error used by the standard calculator functions, error () prints the standard
error message, with the string inserted into the variable portion of the standard message, if any.
3. If n is less than zero, error() prints the negative number and ignores the message string. This is useful
for debugging and for reporting internal errors
The SAGET library enhances the functionality of the standard ADS library. It provides a set of input
functions equivalent to the standard ADS input functions ads_getxxx() plus some related utility
functions.
The extended user-input functions take exactly the same parameters and work exactly the same as their
ADS counterparts. However , they provide addional functionality, as follows:
If you want to use the SAGET library in your ADS application, you must include the header file saget.c in
your source files and compile your ADS application along with the source files saget.c and util.c. you can
look at these source files to see how this library is implemented.