2_Programming in AutoLISP

117

Transcript of 2_Programming in AutoLISP

Page 1: 2_Programming in AutoLISP
Page 2: 2_Programming in AutoLISP

Published by CFS Documentation cellDivision of Centre for Electronics Design and Technology of IndiaA Scientific Society of Department of Electronics,Govt. of India,New Delhi.

First Edition: 1999

TRADE MARKS: All brand name and product names mentioned in this book are trade marks or registered trade mark oftheir respective companies.

Every effort has been made to supply complete and accurate information. However, CEDTI assumes no responsibility for itsuse, 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

Page 3: 2_Programming in AutoLISP

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.

Page 4: 2_Programming in AutoLISP

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)

Page 5: 2_Programming in AutoLISP

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 integersare 32 bit signed numbers with values ranging from + 2,147,483 to - 2,147. AutoLISPuses 32 bit internally; those transferred between AutoLISP and AutoCAD are restrictedto 16 bit values and hence the user can pass integer values ranging from - 32,768 to +32,767 only.

e.g.: 23, 45, -32768

1.2 REAL

A real number is a number containing a decimal point (i.e., floating point numbers) andcan be either positive or negative. Real numbers are stored in double precision floatingpoint format, providing at least 14 significant digits of precision, even through theAutoCAD command line areas shows only 6 significant digits.

e.g.: 34, 56, 123, -29.9,-3.0

1.3 STRING

A string is a group of characters enclosed within quoted strings. The backslash allowscontrol characters or escape code to be included within the string. Individual strings arelimited to 132 characters.

e.g. :“cadd”, “CADD”, “123”, “A123”, A123” “\nEnter first point”

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.

e.g.: (3 2 4) (a b c d), (1 “ONE”)

1.5 SYMBOL

A symbol is a character or a collection of alphanumeric and notation characters exceptthe following: (), ., `,” and;. A symbol name cannot consists of only numeric characters.

Page 6: 2_Programming in AutoLISP

e.g.: a, xyz, a1, p1

1.6 FILE DESCRIPTOR

File descriptors are alphanumeric labels assigned to files opened by AutoLISP. When anAutoLISP 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: (open “text.dat” “r”)<File: #53478>

1.7 ENTITY NAMES

An entity name is a number assigned to objects in a drawing. It is actually a pointer to afile maintained by AutoCAD from which AutoLISP can find the object’s database recordand its vectors. This label can be referenced by AutoLISP functions to allow a selectionof objects for processing in various ways. The following example uses the “entlast”,function to get the name of the last object entered into the drawing.

Command: (entlast)<File name: 60000016>

1.8 SELECTION SETS

Selection sets are groups of one or more objects. You can interactively add objects to ormore objects from selection sets, with AutoLISP routines.

1.9 SURBS AND EXTERNAL SUBRS

Most of the AutoLISP functions are built-in subroutines called SUBRS. The functionsdefined by external ADS and ARX applications are called EXTERNAL SUBRS. Thenames of Subrs and External subrs are not case sensitive.

For example the “princ” function is a Subrs. The “acad_strlsort” function is Externalsubrs.

1.10 CONSTANTS

When you explicitly use a data type in an AutoLISP expression that value is known in aconstant. There is a predefined constant pi evaluating to 3.14159 and a symbol Tevaluating to “TRUE”. Constants should not be used as symbols. For example in thefollowing expression the symbol “a” is set to a constant value “CADD”.

Page 7: 2_Programming in AutoLISP

Command: (setq a “CADD”)

1.11 CONVENTIONS OF AUTOLISP

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 areconsiderably easier when you load the AutoLISP code from a file rather than re-enter iteach time when you make a refinement.

• AutoLISP follows the prefix notation . i.e., the function name should precede thearguments. 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 canitself 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)

• The following characters terminate a symbol name or a numeric constant (), `, “, ; ,(space) and end of line)

• More than one blank space in an expression is considered as a single space.

e.g. ( + 2 3 ), ( + 2 3) 7)

• An AutoLISP expression or a function should start with a open or left parternershipi.e., “(“and end with a close or right parenthesis”)”.

• Symbol and function names are not case sensitive, i.e., you may use upper or lower

case characters.

• Numerals can be preceded by an optional “+” or “-” sign.

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

Page 8: 2_Programming in AutoLISP

• Expressions nested within other expressions return their result to the surroundingexpressions. AutoLISP evaluates from the innermost expression and returns thevalue to the surrounding expressions.

e.g. (+ (*3 2) (/ (+1.5 2.5))) returns 8.0

• Comments can be included in a program and they should begin with a semicolon “ ; ”

e.g. (+ 5 3 ) ; This is an Addition

• Variables can be evaluated at the “Command prompt” in autoCAD with a preceding“!” symbol.

e.g. (seta 1 3)Command: !a returns 3

2. ARITHMETIC AND TRIGONOMETRIC FUNCTIONS

2.1 ARITHMETIC FUNCTIONS

Thee are four functions under this group. The arguments for these function can benumbers, variables, symbols and constants. If any one argument is real then the resultwill be a real value. If all the arguments are integers then the result will be an integer.

Syntax : (+ <num1> <num2>...)

This function returns the sum of all numbers, which are real or integer. If all numbers areintegers then the result is an integer value. If any one number is a real number then theresult will be a real value.

e.g.

Command: (+ 5 3) returns 8

(+ 6.2 3) returns 9.2

(+ 8.75 -4) returns 4.75

(+ 5. 7 9) returns 21.0

Syntax: (- <num1> <num2>...)

Page 9: 2_Programming in AutoLISP

This function returns the result after subtracting <num2> from <num1>. If more than twonumbers are given as arguments then the result will be the sum of second and theremaining arguments subtracted from <num1>. If only one argument is present then theresult will be the value of <num1> subtraced from 0.

e.g.Command: (- 5 4) returns 1

(- 5.5 2) returns 5.5

(- 8 6 4) returns -2

(- 10 -5) returns 15

(- 3) returns -3

Syntax: ( <num1> <num2>...)

This function returns the product of all operands. If only one <num> is given then thisfunction returns the result of multiplying it by one and supplying no arguments returnsthe result zero.

e.g.

Command: (* 5 4) returns 20

(* 5.5 2) returns 11.0

(* 1 2 3) returns 6

Syntax: (/ <num1> <num2>...)

This function returns the quotient by dividing <num1> by <num>. If more than twooperands 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 noarguments returns zero.

e.g.

Command: (/ 5 4) returns 1

(/ 5 4.0) returns 1.25

(/ 12 2 3) returns 2

2.2 TRIGONOMETRIC FUNCTIONS

Page 10: 2_Programming in AutoLISP

There are three functions under this group. Using these basic. Trigonometric functionsyou 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

(sin 2) returns 0.909297

Cos

Syntax: (cos <angle>)

This function returns the cosine value of <angle> as a real value. The <angle> argumentmust be expressed in RADIANS.

e.g.Command: (cos 0) returns 1.0

(cos 6) returns 0.96017atan

Syntax: (atan <num1> [<num2>|)

This function returns the arctangent value of <num1> in RADIANS .

The result is tan inverse of <num1>. If both <num1> and <num2> are supplied then thisfunction returns the arctangent of <num1> divided by <num2> in RADIANS .

e.g.

Command: (atan 1.0) returns 0.785398

(atan 2.0 3.0) returns 0.588003

Page 11: 2_Programming in AutoLISP

3. BASIC STRUCTURE FUNCTIONS

abs

Syntax: (abs <number>)

This function returns the absolute value of a <number>.

e.g.Command: (abs -4) returns 4

(abs 25) returns 25

(abs -3.425) returns 3.425sqrt

Syntax: (sqrt <number>)

This function returns the square root of <number> as a real number.

e.g.Command: (sqrt 16) returns 4.0

(sqrt 2025.0) returns 45.0

log

Syntax: (log <number>)

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

Page 12: 2_Programming in AutoLISP

(log 2.71828) returns 0.999999exp

Syntax: (exp <number>)

This function returns the value of the e raised to the specified number (the antilogarithmof <number>).

e.g.Command: (exp 0) returns 1.0

(exp 1) returns 2.71828

expt

Syntax: (expt <base> <power>)

This function returns the value of <base> raised to the specified <power>. Thearguments may be integer to real.

e.g.Command: (expt 2 2 ) returns 4

(expt 2.0.3) returns 8.0

(expt (* 4 5) (/4 2 ) ) returns 400

max

Syntax: (max <num1> <num2>....)

e.g.Command: (expt 4 5 3) returns 5

(expt 2. 0.1 1.2) returns 2.0

min

Syntax: (min <num1> <num2>.....)

This function returns the minimum numeric value in the given set of arguments. Thearguments may be signed real or integers.

e.g.

Command: (min 3 2 1) returns 1

Page 13: 2_Programming in AutoLISP

(min -2 1.2 -0.5) returns -2.0

5. LIST HANDLING FUNCTIONS

List provide an efficient method of storing numerous related values.

car

Syntax: (car <list>)

This function returns the element of the <list>. If the list is empty then the functionreturns nil.

e.g.Command: (setq L1 (list 2 “A” 32 “B”)) returns (2 “A” 32 “B”)

(car L1) returns 2

(setq L2 (list (list 2 3) (list 4 4) ) ) returns ( (2 3) (4 4) )

(car L2) returns (2 3)cdr

Syntax : (car <list>)

This function returns a list which contains all the elements of <list>, except the elementof the list.

Page 14: 2_Programming in AutoLISP

��

e.g.Command: (setq L (list 1 2 3 4) ) returns (1 2 3 4)

(cdr L) returns (2 3 4) )

(setq m (list (list 2 3 4) (list 2 3 4 ) returns ( (2 3) (4 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 concentrationsare as shown below:-

cadr caddr cadddr caar caaar caaaar cadar and so on

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)

(caddr is (car (cdr L) hence returns 2

(caddr L) is (cdr (cdr L) which returns (3)

length

Syntax : (length <list>)

This function returns the number of elements in the <list> as an integer.

e.g.Command: (setq L (list 1 2 “A” ) ) returns (1 2 “A”)

(length L) returns 3

(setq m (list 1 (list 2 3) ) returns (1 (2 3) )

(length m) returns 2

Page 15: 2_Programming in AutoLISP

��

last

Syntax: (last <list>)

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

(last L) returns “A”

nth

Syntax: (nth <index> <list>)

This function returns the indexed element of the <list>. The element of the <list> willalways have an index 0. The second element has an index 1, the third element has anindex 2 ans so on.

e.g.

Command: (setq L (list 1 2 “C” “A” ) ) returns (1 2 “C” “A”)

(nth 0 L) returns 1

(nth 1 L) returns 2

(nth 2 L) returns “C”

(nth 6 L) returns nil

reverse

Syntax: (reverse <list>

It returns the <list> by rearranging the elements in reverse order.

e.g.

Command: (setq L (list 1 2 3 4 ) ) returns (1 2 3 4)

(reverse L) returns (4 3 2 1)

(setq m <list 1 (list 2 3) “A”) ) returns 1 (2 3) “A”

(reverse m) returns (“A” (2 3) 1)

member

Page 16: 2_Programming in AutoLISP

��

Syntax: (member <item> <list>

This scans through the <list> for the occurrence of the <item> and returns the remainingportion of the list starting from the first occurrence of the <item>. The function returnsNIL, if the <item> is not found in the <list>.

e.g.

Command: (setq L (list 1 2 3 “A” “B” ) ) returns (1 2 3 “A” “B”)

(reverse L) returns (4 3 2 1)

(setq m <list 1 (list 2 3) “A”) ) returns 1 (2 3) “A”

(reverse m) returns (“A” (2 3) 1)

member

Syntax: (member <item> <list>

This scans through the <list> for the occurrence of the <item> and returns the remainingportion of the list starting from the first occurrence of the <item>. The function returnsNIL, if the <item> is not found in the <list>.

e.g.

Command: (setq L (list 1 2 3 “A” “B” ) ) returns (1 2 3 “A”“B”)

(member 3 L) returns (3 “A” “B”)

(member 5 L) returns nil

(setq m (list (list 2 3) (list 6 7) 8) ) returns (2 3) (6 7) 8)

(member (list 6 7) m) returns ( ( 6 7 8)

append

Syntax: (append <list1> <list2>....<listn>)

This function combines all the given arguments and forms a single list in the given order.

e.g.

Command: (setq L `(1 2) L2 `(3 4) )

(append L1 L2) returns (1 2 3 4)

(append L1 L2) returns ((1) (2) (3))

Page 17: 2_Programming in AutoLISP

��

subst

Syntax: (subst <newitem> <old item> <list>

This function substitutes a <newitem> in the place of the <olditem> in the list and returnsthe modified list. If the <olditem> does not exist in the given list then the original list isreturned.

e.g.

Command: (setq L `(1 2) (3 4) 1)) returns (1 2 (3 4) 1)

(subst `0 `1 a) returns (0 1 2 (3 4) 0)

(subst `3’ `(3 4) a) returns (1 2 3 1)

acad_strlsort

Syntax: (acad_strlsort <list>)

This function sorts a <list> of string by alphabetical order. This will be useful when theuser presents a list containing Layers, Blocks or File names in a scrolling list box orpopup list within a dialog box.

e.g.

Command:(acad_strlsort `(Sunday” “Monday” “Tuesday” “Wednesday”“Thursday” “Friday” “Saturday”

will return

(“Fdiday” “ Monday” “ Satuday” “Sunday” “Thursday” “Tuesday”“Wednesday”)

Page 18: 2_Programming in AutoLISP

��

6. PROGRAM CONTROL FUNCTIONS

Syntax: (= <atom1> <atom2> [<atom3>...) )

This function checks for equality and returns T if all <atom>s are numerically equal andNIL otherwise. The arguments can be either a number or a string.

e.g.

Command: (= 4 4.0) return T

(= “cadd” “cadd” return T

(= “CADD” “cadd”) returns nil

(= 45 44.999) returns nil

/ =

Syntax: (/= <atom1> atom2> [<atom3>...])

This function checks for inequality and returns T if all the specified <atom>s are notnumerically equal and NIL otherwise.

e.g.

Command: (/ = 100 108) returns T

(/ = “Cadd” “Cadd”) returns nil

(/= “a” “b” “c”) returns T<

Syntax: (< <atom1> <atom2> [atom3>....])

This function checks and returns T if <atom1> is less than <atom2> and NIL otherwise. Ifmore 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.

Command: (<50 45) returns nil

(<“a” “b”) returns T

(<2 3 8 8) returns nil

(< 3 4 5 5) returns nil

Page 19: 2_Programming in AutoLISP

��

< =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 orEQUAL TO the <atom> to its right.

e.g. (< = 11 12) returns T

(< = “Cadd” “cadd”) returns T

(< = 2 3 4 4) returns T

(< = 88 66 33) returns nil

>

Syntax: (>= <atom1> <atom2> [<atom3>...])

This checks and returns T if <atom1> is greater than or equal to <atom2> and nillotherwise. If more than two <atom>s are given then T is returned, if each <atom> isGREATER THAN or EQUAL TO the <atom> to its right.

e.g. (> 50 40) returns T

(> “Caadd” “cadd”) returns nil

> =

Syntax: (>= <atom1> <atom2> [<atom3>...])

This checks and returns T if <atom1> is greater than or equal to <atom2> and nilotherwise. If more than two <atom>s are given then T is returned, if each <atom> isGREATER THAN or EQUAL TO the <atom> to its right.

e.g. (> = 50 40) returns T

(> = 5 4 3 2) returns T

(> = 45 3 2) returns nil

(> = “b” “c”) returns nil

eq

Syntax: (eg <expr1> <expr2>)

Page 20: 2_Programming in AutoLISP

��

This function returns, T if the two expressions given are identical. Otherwise it returnsNIL. This function determines whether <expr1> and <expr2> are bound to the sameobject.

e.g.

Command: (setq a `(1 2 3) b `(1 2 3) c b) (eq a c) returns nil

This returns nil because a and c are not the same lists.

(eq b c) returns nil

This returns T if a and b are exactly the same.

equal

Syntax: (equal <expr1> <expr2> [<fuzz>])

This function returns T, if the two expressions evaluate to the same value. This is not thesame as eq function. the optional parameter <fuzz> denotes the maximum amount bywhich the <expr1> and <expr2> can differ and still be considered equal.

e.g.

Command: (setq a(*3 2) b (*6 1) )

(equal a b) returns T

(equal `a `b) returns nil

e.g.

Command: (setq a 5.34679105)

(setq b 5.34678106)

(equal a b 0.00000001) return T

minusp

Syntax: (minusp <item>)

This function returns, T if the specified <item> is negative and otherwise it returns NIL.

e.g.

Command: (minusp -1) returns T

Page 21: 2_Programming in AutoLISP

��

(minusp -3,4) returns T

(minusp 4) returns nil

boundp

Syntax: (boundp <item>)

This function returns T, if the specified <item> is bound to a symbol and returns NIL if novalue is bound to the <item>. If the <item> is an undefined symbol then it isautomatically created and is bound to NIL.

e.g.

Command: (setq a 1 b bil)

(boundp `a) returns T

(boundp `b) returns nil

zerop

Syntax: (zerop <item>)

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

(zerop b) returns nil

(zero 0.1) returns nillistp

Syntax: (listp <item>)

This function returns T, if the specified <item> is a list. Otherwise it returns NIL.

e.g.

Command: (setq a `( (2 3) 4 5) )

Page 22: 2_Programming in AutoLISP

��

(listp a) returns T

(listp (cadr a) ) returns T

(listp `a) retuns niltype

Syntax: (type <item>)

This function checks the data type of the specified <item>. The allowed data types are:

TYPE DESCRIPTION

REAL Floating-point numbers

FILE File descriptors

STR Strings

INT Integers

SYM Symbols

LIST Lists

SUBR Internal functions

PICKSET Selection sets

ENAME Entity names

PAGETB Function paging tablee.g.

Command: (setq a 1 b 4.5 d `(1 2 3) )

(type a) returns INT

(type b) returns REAL

(type d) returns LIST

(type - ) returns SUBR

(type c) returns nil

6.1 LOGICAL OPERATORS

Syntax: (and <expr1> <expr2>....)

Page 23: 2_Programming in AutoLISP

��

This function returns T if all the <expr>s evaluate to a non nil value. It returns NIL, if anyone of the given <expr>s evaluate to NIL and ceases further evaluation. You can alsosupply variable names as <expr>s.

e.g.

Command: (setq a 5 b 10 c nil)

(and (> a 2) (< b 25 ) 0 returns T

(and (= a 5) (= c 05) ) returns nil

(and a b) returns T

(and a b c) returns nil

or

Syntax: (for <expr1> <expr2>...)

The function returns the value T, if any one or all the <expr>s in the argument listevaluate 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.

Command: (setq x 10 y 20 z 30 a nil b nl)

(or (= x 10) (= y 2) ) returns T

(or (= x 10) (= y 20) ) returns T

(or (= x 11) (= y 21) ) returns nil

(or x ( (= y 20) ) returns T

(or x y) returns T

(or a b) returns nil

Page 24: 2_Programming in AutoLISP

��

7. STRING HANDLING FUNCTIONS

String is a group of characters enclosed within quotation marks. A single string value islimited to 132 characters. Strings of unlimited length can be created by joining the stringstogether and control characters can also be included within quoted strings. Applicationscan also compare a string to a wild-card pattern and this facility is widely used when youare building a selection set and retrieving the entirely data by application name.

strcase

Syntax: (strcase <string> [<which>])

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 orevaluated to NIL, the <string> is converted to upper case. Otherwise it is converted tolower case characters.

e.g.

Command: (strcase “Hello”) returns “HELLO”

(strcase “HELLo” 1) returns “hello”strcat

Syntax: (strcat <string1> string2>...)

This function combines multiple strings into a single string vlaue Blank and null stringscan also be combined.

e.g.

Command: (strcat “cadd” “centre”) returns “cadcentre”

(strcat “cadd” “ “ “centre” returns “cadd centre”

strlen

Syntax: (strlen <string>)

This function returns the number of characters in the specified <string>. Blank spacesare also considered as valid characters.

e.g.

Command: (strlen “AutoCAD Mechanical Desktop”) returns 26

Page 25: 2_Programming in AutoLISP

��

(strlen “cadd”) returns 5

(strlen “ “) returns 1

substr

Syntax: (substr <string> <strt> [<length>])

This function returns the substring of a <string>. The <star> argument specifies the firstcharacter of the string to be included the substring. The number of characters to beincluded in the substring is specified by <length>. If <length> is not specified then thefunction returns all characters including the following the specified <star> character.

e.g.

Command: (substr “strength” 3 4) returns “reng”

(substr “strength” 3) returns “rength”

(substr “cadd centre” 3) returns “dd centre”

(substr “cadd centre” 3 4) returns “dd c”

(substr “cadd centre” 1) returns “cadd centre”

(substr “cadd centre” 10) returns “re”

wcmatch

Syntax: (wcmatch <string> <match>)

This function enables the application to compare a <string> to a wild-card pattern. If thestring matches with the pattern then this function returns T else NIL. The wild-cardpatterns 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 functioncompares the first 500 characters of the <string> and <match> specified.

The <match> can contain the wild-card matching characters shown in the followingtable:

CHAR DEFINITION

# Matches any single numeric digit.

@ Matches any alphabetic character.

Page 26: 2_Programming in AutoLISP

��

. Matches any single non alphanumeric character

* Matches any character sequence including an empty string andcan be used anywhere in the search pattern.

? Matches any single character.

~ Matches any thing other than the next character.

[..] Matches any one of the characters inside.

[~..] Matches any one character except those enclosed.

- Used in [ ] to specify a range of characters.

, Separates any two patterns.

` Escapes special characters.

The following example tests the string with the patterns.

e.g.

Command: (wcmatch “Name” “N*”) returnsT

(wcmatch “Name” ???,~*m*,N*”) returns T

(wcmatch “Name” “*”, *”) returns NIL

read

Syntax: (read< string>)

This function returns the first atom or list in the specified <string>. The <string> cannotcontain blank spaces except within list or string.

e.g.

Command: (read “end”) returns end

(read “end of”) returns end

In the above case from the string “end of” only end is returned as, a blank space isencountered after the first word.

Page 27: 2_Programming in AutoLISP

��

8. CONVERSION FUNCTIONS

The functions convert data types and units. AutoLISP also provides functions to handledecimal ASCII codes.

atof

Syntax: (atof <item>)

This function returns the conversion of a string to a real value.

e.g.

Command: (atof “3.4”) returns 3.4

(atof “5’ returns 5.0

atoi

Syntax: (atoi <item>)

This function returns the conversion of a string to an integer.

e.g.

Command: (atoi “34”) returns 34

(atoi “5.0”) returns 5

itoa

Syntax: (itoa <item>)

This function returns the integer <item> given as arguemnt into a string.

e.g.

Command: (itoa 34) returns “34”

rtos

Syntax: (rtos <number>[mode>] [precision>])

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.

The following are the <mode> argument values:

Page 28: 2_Programming in AutoLISP

��

MODE EDITING FORMAT

1. Scientific2. Decimal3. 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 andLUPRECA are used.

e.g.

Command: (rtos 3.4) returns “3.4000”

(rtos 5 2 2) returns “5.00”

(rtos 3.5 4) returns “3 1/2”

(rtos 2.5 1 2) returns “2.50 E+00”

ascii

Syntax: (ascii <string>)

This function returns the ascii code of the first character of the <string>.

e.g.

Command: (ascii “A”) returns 65

(ascii “CADD” returns 67 (ASCII coee of “C”

angtos

Syntax: (angtos <angle> [<mode>[ ]<precision>])

This function is used to convert the specified <angle> to a string depending on thesettings of <mode> and <precision>. The arguments <mode> and <precision> must beinteger values. The following are the <mode> argument values:

MODE EDITING FORMAT

0 Degrees1 Degrees/minutes/seconds2 Grads

Page 29: 2_Programming in AutoLISP

��

3 Radians4 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 andAUPREC are used.

e.g.

Command: (setq a (angle (` 2 4 ) ` (2 2) ) )

(angtos a 0 0) returns “270”

(angtos a 1 0) returns “270d”

(angtos a 0 4) returns “270.0000”

(angtos a 3 3) returns “4.712r”

chr

Syntax: (chr <integer>)

This function returns the ASCII characters corresponding to the integer given asargument. The value returned is a string.

e.g.

Command: (chr 65) returns “A”

(chr 97) returns “a”

rem

Syntax: (ren <num1><num2...)

This function divides <num1> by <num2>. If there are more than two arguments then theremainder of FIRST and SECOND is divided by the THIRD and the value will bereturned.

e.g.

Command: (rem 5 4) returns 1

(rem 5 4.0) returns 1.0

(rem 20 7 4) returns 2

i.e., (rem 20 7 4) is (rem 20 7 4)

Page 30: 2_Programming in AutoLISP

��

fix

Syntax: (fix <number>)

This function returns the truncated value of the <number> as an integer after discardingthe decimals. The arguments may be signed real or integer values.

e.g.

Command: (fix 8) returns 8

(fix 1.32) returns 1

(fix 2.895) returns 2

(fix -5.85) returns 5

float

Syntax: (float <number>)

This function returns the conversion of the <number> into a real. the <number> may besigned real or integer value.

e.g.

Command: (float 2) returns 2.0

(float 8.959) returns 8.959

(float -5) returns 5.0

1 +

Syntax: (1+ <number>)

This function returns the <number> increased by 1. The <number> may be a real or aninteger value.

e.g.

Command: (1+ 5) returns 6

(1+ 6.75) returns 7.75

Page 31: 2_Programming in AutoLISP

��

1 -

Syntax: (1+ <number>)

This function returns the <number> increased by 1. The <number> may be a real or aninteger value.

e.g.

Command: (1- 5) returns 4

(1- 6.75) returns 5.75

quote

Syntax: (quote <expr>)

1 +

Syntax: (1+ <number>)

This function returns the <expr> as a symbol without evaluating it. The function can alsobe represented by a “ ‘ “

e.g.

Command: (quote A) returns A

`(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 Commandprompt just like a built-in AutoCAD command. You can use this feature to add newcommands to AutoCAD or to redefine existing commands. To use the functions asAutoCAD commands the function name must use the form C:XXX when XXX is thefunction name which must be defined without arguments.

A function defined with C:XXX can also be invoked transparently preceded by a singlequote (`) from which any prompt of built-in AutoCAD command provided the functiondoes 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

Page 32: 2_Programming in AutoLISP

��

C: Hello

Hello is now defined as a command. To execute the command Hello, specify thecommand 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: LINEFrom point: HelloHello WorldFrom point:

e.g. 2

Command : (defun box (sp L w / ap1 sp2 sp3)

(setp sp1 (list (+ (car sp) L) (cadr sp) )

sp2 (list (car sp1) (+ (cadr sp1 w) )

sp3 (list (car sp) (cadr sp2) ) )

(command “pline: sp sp1 sp2 sp3 “c”)

)

In the above function the “sp, L,w” are arguments and “sp1, sp2, sp3” are local variablesfor the function. These variables lose their values after the function is executed.

Local Symbols in Functions

AutoLISP allows you to define a list of symbols that are variable only to that function andthese are known as local symbols. The use of local symbols ensures that the variablesin your functions are unaffected by the surrounding application and that your variablesare not available after the function has completed the task.

The following example shows the use of local symbols in an user-defined function:

Command: (Defun sample (/ a b)

(Setq a “CADD” b “CENTRE”)

(Princ (strcat “\n a has the value:” a))

(Princ (strcat “\n b has the value: “b”))

Page 33: 2_Programming in AutoLISP

��

(princ)

)

Before you test this new function assign variables “a” and “b” to values other thanthose 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 theexclamation point( ! ).

Command: !a

1

Command: !b

2

List

Syntax: (list <exp1> expr2>...)

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 2Dor 3D point variable (a list of two or three real).

e.g.Command: (list 5 10.0) returns (5 10.0)

(list “A” “B”) returns (“A” “B”)

(list 5 “A”) returns ( 5 “A”)

(list `A `B) returns (A B)

(list (list 5 10) ) returns ((5 10))

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

Page 34: 2_Programming in AutoLISP

��

(setq L (list“C” “A” “D” “D”) returns (“C” “A” “D” “D”)

(setq K L returns ((1 2 3) (“C” “A” “D” “D”))

Polar

Syntax: (polar <point> <angle> <distance>)

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 a3D point, <angle> is always with respect to the current construction plane. The point is alist of two real.

e.g.

Command: (polar `(2 2) 0 3) returns (5.0 2.0)

The new point is fixed at an angle 0, at a distance of 3 units from the point 2,2.

Command: (polar (`2 2) 0.785398 1.414) returns (3.0 3.0)

The new point is located at an angle of 45 degrees (denoted as 0.785398 in radianmeasure) at a distance of 1.414 from 2,2.

angle

Syntax: (angle <pt1> <pt2>)

This function returns the angle between the two given points in RADIANS. The angle ismeasured from X axis of current construction plane and if a 3D point is supplied thenthey are project onto the current construction plane.

e.g.Command: (angle `(2 2) `(3 3)) returns 0.785398

(corresponds to 45 degrees)

(angle `(2 2) `(3 4)) returns 1.5707

(corresponds to 90 degrees)

(angle `(2 2) `(4 2)) returns 0.0

(corresponds of 0 degrees)distance

Syntax: (distance <pt> <pt2>)

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.

Page 35: 2_Programming in AutoLISP

��

e.g.

Command: (setq P1 `(2 2) P2 `(2 4))

(distance P1 P2) returns 2.0

(setq P1 `(2 0 0) P2 `(0 0 2 )) (distance P1 P2) returns 2.82843

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 anoptimum design solution. In conventional design process, an engineer has to repeatedlyrefer 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, oneneed not look the design data table. All the necessary data can be stored as data filesand 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 eithermanually or through some other means

AutoLISP provides powerful yet simple functions to search and access the datafiles, read and write/append information on to the data file.

A file can be opened and read/modified anywhere in a program. When you opena file, AutoLISP provides a pointer which has to be assigned to a variable for furtherreference.

The functions included in this chapter are as listed below.

The functions included in this chapter are,

findfile open close

read-line write-line read-char

write-char getfiled

findfile

Searches the AutoCAD library path for the specified file

findfile <file name>)

Returns:

Page 36: 2_Programming in AutoLISP

��

If the file is found Path of file as a STRING

If the file is not found nil

The FINDFILE function searches for the given file whose name is given as thestring argument in the AutoCAD library path. The file name should also include theextension of the file. If the drive or directory prefix is given then the file is searched onlyin the specified drive or directory.

Example:

If there is a file named “shaft.lsp” in the path c:\acadr14,then,

Command: (findfile “shaft.lsp”)

“C:\\ACADR14\\shaft.lsp”otherwise,

Command: (findfile “shaft.lsp”)

Nil

Open

Opens a file for access by the AutoLISP I/O functions

(open <filename> <mode>

Returns:

If the file is found File Pointer (descriptor)

If the file is not found nil

The filename argument is a string that specifies the name and extension of thefile to be opened. The mode argument is the read/write flag. It must be a stringcontaining a single lower case letter. The following table describes the valid modeletters.

Open mode Description

“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 andopened. If filename already exists, Its existing data is overwritten.

“a” Open for appending. If filename does not exit, a new file is created a newfile is created and opened. If filename already exists, it is opened and the

Page 37: 2_Programming in AutoLISP

��

pointer is positioned at the end of the existing data, so new data you writeto the file is appended to the existing data.

Open function returns a file description to be used by the other I/O functions. Thefile 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,

Command: (setq f (open “new.txt” “w”)

<File: # 22712c6>Command: (setq f(open “nosuch.fil” “r”))nilCommand: (setq f (open “lofgile” “a”))<File: # 22711d8>

When a file “data.txt” exists,

Command: (setq f (open “data.txt” “r”))<File: # 227115a>

Close

Closes an open file

(close <file descriptor>)

Returns

on success nil

on failure error message

The <file descriptor> argument is a file descriptor obtained from the openfunction. After a close, the file descriptor is unchanged but is no longer valid. All filesopened 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 thevariable no_lines equal to that number:

(setq fil_id(open “check.txt” “r”) no_lines 0)(while (read-linefil_id) (setq no_lines ( 1 + no_lines)))(close fil_id)

Page 38: 2_Programming in AutoLISP

��

read – char

Returns the ASCII code of the character read from an open file or from keyboard.

(read-char [<file descriptor>])

Returns

on success nil

on failure error message

This function returns the decimal ASCII code representing the character readfrom the keyboard input buffer or from an open file described by the <file descriptor>. Ifthere are no <file descriptor>s and characters in the keyboard input buffer, the functionwaits for a keyboard input.

Example

Command: (setq f (open “data.txt” “r”))<file: # 227115a>Command: (read-char f)106

write – char

Writes a character to the screen or to an open file

(write – char <num> [<file descriptor>])

Returns

on success write the character

on failure error message

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 <filedescriptor> is given then the character is written on the screen else the character will bewritten to the specified file.

Example

Command: (write – char 65)A

Command: setq fp O(open “data.txt” “a” ))<File: # 22713fa>Command: (write – char 65 fp)

Page 39: 2_Programming in AutoLISP

��

The last example writes character A onto the open file whose <file descriptor> isfp. In either case, WRITE – CHAR will echo the argument (65 in this case) at theCommand: prompt

read – line

Reads a string from the keyboard or from an open file.

(read – line [<file descriptor>])

Returns

on success line read as string

on failure nil

This function returns the line read from the keyboard or from an open file. Whenthis function is repeated with the file descriptor then the function returns the next line ofthe file.

Example

Assuming that fp is a valid open file pointer,

(read-line fp)

returns the next input line from the file, or returns nil if the end-of-file has beenreached.

write – line

Writes a string to the screen or to an open file

(write – line <string> [<file descriptor>])

Returns:on success string omitting the quotes

on failure error messageThis function write the <string> to the screen or to an open file. The function

returns a quoted string to the file if <file descriptor> is specified. Otherwise the <string>is written on the screen

Example

Assuming that fp is a valid open file descriptor.

(write – line “Welcome” fp)

writes Welcome in the file.

Page 40: 2_Programming in AutoLISP

��

getfiled

Display the standard AutoCAD file dialog box, and returns that the name

(getfiled <title> <default> <ext> <flags>)

Returns

If file is selected the file selected as string

If file not selected nil

The <title> argument specifies the dialog box label. The <default> argumentsspecifies 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 filespresented to the user in a scrolling list box. This function returns the name of theselected by the user, or nil if no file was selected. The <flags> argument is an integervalue ( a bit-coded field), the meaning of the various bit values are:

Bit Value Meaning

1. Display “alert” message if the user selects an existing file.2. Disables the “Type It” button in the dialog box.4. Allows the user to change the file extension or no extension at all.8. Performs an AutoCAD library search for the filename entered.

Example:

Command: (getfiled “Select a Lisp File” “c:\acadr14” “lsp” 8)“C:\\ACADR14\\Surf.lsp”

If you choose a file from the dialog box and click on OK then AutoCAD returnsthe 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.

Page 41: 2_Programming in AutoLISP

��

The entlast function is frequently used to obtain the name of a new entity that hasjust been added with the command function. The entity need not be on the screen or ona thawed layer to be selected.

Example:

(setq e1 (entlast))

Sets e1 to the name of the last drawn entity in the drawing.

entnext

Returns the name of the next object (entityO in the drawing.

(entnext [<ename>])

Returns:

if next entity is found The Entity name of the entity

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 indatabase, else it returns the name of the seceding entity specified by <ename>.

Example

(setq e1 (entnext))

returns the entity name of the first entity in the drawing.

(setq e2 (entnext e1))

returns the entity name of the entity following e1.

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

Entity not found nil

Page 42: 2_Programming in AutoLISP

��

This function is used to select an entity by specifying a point. The function returnsa 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 waitsfor user input. When it is not specified, AutoCAD displays a default prompt SelectObject: in the command prompt are:

Example:Assuming if there is an object passing through point 3,3Command: (entsel “Pick entity:”)

Pick entity: 3,3

(<Entity name: Ce74h3> (3.000000 3.000000 0.0))

nentsel

Prompts the user to select an object (entity) by specifying a point, and provides accessto 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

Entity not found nil

This function provides access to the entities contained inside a nested entity.(such as POLYLINES and INSERTS) If the optional argument <prompt> is passed thenthis function waits for user selection by issuing <prompt> or else a standard promptSelect Object: will be issued. If the selected objet is not a nested entity (i.e. neither aPOLYLINE nor a BLOCK INSERT) then this function returns same information asENTSELF function. When a sub entity of a nested entity is selected, this function returnsa list containing 4 elements.

The first element of that list will be entity name of the selected subentity. Thesecond element will be the point of selection, third one will be a matrix called `Model toWorld Transformation Matrix’ which specifies the location of the sub entity with respectto the insertion point of the block. The fourth member of the above list will be entity nameof the block that contains the selected sub entity.

If the selected entity is an ATTRIBUTE of an INSERT then this function returnsonly the entity name of the attribute and the pick point.

The nentsel function will be a list as follows:

(<Entity name: ename1> Name of entity(Px Py Pz) Pick point((X0 Y0 Z0)(X1 Y1 Z1) Model to World transformation matrix(X2 Y2 Z2)(X3 Y3 Z)

Page 43: 2_Programming in AutoLISP

��

)(<Entity name: ename2> Name of most deeply nested block containingselected entity

<Entity name: ename>) Name of outermost block containingselected entity.)

entupd

Updates the screen image of an object (entity)

(entupd <ename>)

Returns

on success The Entity name

When a polyline vertex or block attribute is modified with entmod, the entire complexentity is not updated on the screen. The entupd function can be used to cause a modified polylineor block to be updated on the screen. This function can be called with the entity name of any partof the polyline or block; it need not be the head entity. While entupd is intended for polylines andblocks with attributes, it can be called for any entity. It always regenerates the entity on thescreen, including all subentities.

Example

Assuming that the first entity in the drawing is a polyline with spline fit data andwith several vertices, then

(setq e1 (entnext)) ;Sets e1 to the polyline’s entity name(setq e2 (entnext)) ;Sets e2 to its first vertex(setq en (entget)) ;Sets en to the vertex data(setq ed ;Changes the vertex’s location in en to point(subt (`10 1.0.2.0) ;(1,2)

assoc 10 en) en))

(entmod en) ;Moves the vertex in the drawing(entupd e1) ;Regenerates the polyline entity e1

entmod

Modifies the definition data of an object (entity)

Entmod <elist>)

Page 44: 2_Programming in AutoLISP

��

Returns

on success The Entity list

on failure error message (mostly Bad entmod list).

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

(command “line “ “2,3” “4,5” “ “)(setq en (entnext)

e1 (entget en) ; gets the entity list of the line.

e1(subst (cons 10 (list 4 4))(assoc 10 e1)e1)) ;changes the starting point of the line to 4,4

(entmod e1) ;updates the database

entdel

Deletes objects (entities) or undeletes previously deleted objects.

(entdel <ename>)

Returns

on success The Entity name

on failure error message (bad argument type)

This function is used to delete an entity in the current drawing editor. When usedagain, it undeletes the entity specified by <ename> in the current drawing editor. Alldeleted 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>

If `b’ is not a valid entity name

Command: (entdel b)Error: bad argument type(ENTDEL B)*Cancel*

Page 45: 2_Programming in AutoLISP

��

entmake

Creates a new entity (graphical object) in the drawing

(entmake <elist>)

Returns

on success The Entity

on failure error message (bad entmake list value)

This function creates a new entity in the current drawing making use of the entitylist specified by <elist> as the definition data. If successful then this returns the definitiondata and nil otherwise.

The minimum data <elist> for making an entity are as follows:

1. Entity type

2. Basic geometric data

3. Optional arguments

a. Colorb. Layerc. Linetyped. Extrusion directione. Elevationf. Thickness

1. Valid entity types are “LINE”, CIRCLE”, “ARC”, etc.,

2. Geometric data for:

LINE: Start point & End point

CIRCLE: Center point & Radius

Page 46: 2_Programming in AutoLISP

��

SELECTION SET

SSGET FILTERS

(ssget “X” <filter list>

This function selects all the entities conforming to a specified filter list. The <filterlist> 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 canbe used in a ssget “X” function are,

Code Meaning

0 Entity type2 Block name of block references6 Line type name7 Text style name for text and attribute definitions8 Layer name38 Elevation (real)39 Thickness (real)62 color number (0 => “BYBLOCK”

256 = > “BYLAYER”)66 Attributes – follow flag for block references210 3D extrusion direction vector (list of three reals).

Example:

(ssget “X” (list (cons 0 “line”))) ;selects all lines(ssget “X” (list cons 0 “line”)(cons 8 “C”))) ;selects all lines in the layer named C

sslength

Returns an integer containing the number of objects (entities) in selection set

(sslength) <ss>)

Returns

on success no of entity names present in the set

on failure error message

The number is returned as a real if it is greater than 32, 767. Selection sets nevercontain duplicate selections of the same entity.

Page 47: 2_Programming in AutoLISP

��

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 nameon 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 functionreturns nil.

Example

(setq sd (ssget “X” (list (cons 0 :line”))); place all lines in the selection ; set sd.

(set1 e1 (ssname sd0)) ;selects the first entity in the;selection set sd.

(ssdel e1 sd) ;deletes the lines e1 from the set sd.

sssetfirst

Sets which objects are selected and gripped

(sssetfirst <gripset> [pickset>])

Returns

on success list of the variables passed

on failure error message

Example

The expressions below grips all the entities in the drawing

Command: (setq a (ssget “x”))<Selection set:1>Command: (sssetfirst a)(A)

ssgetfirst

Page 48: 2_Programming in AutoLISP

��

Determines which objects are selected and gripped(ssgetfirst

Returns

on success list of the selection sets (gripped / selected)

on failure error message

Example

Command: (ssgetfirst)[<Selection set: 2> nil)

APPLICATION HANDLING

Almost all environments and software provide the user the tools to develop applicationsfor his/her need through customization. It is appropriate because it is very difficult or ratherimpractical 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 developedAutoCAD with an open architecture, which encourages customizing to a large extent.

Autodesk has considered both the noise and experienced user has given tools for variouslevels of customization. It depends on the knowledge and experience of the user, in AutoCAD aswell as other programming language such as AutoLISP and C. It is also based on the nature andcomplexity of the application to the developed.

AutoCAD can be customized through,

¾¾ AutoLISP, a programming language framed by the Autodesk for developing smallapplications involving either designing or drafting in AutoCAD.

¾¾ ADS – AutoCAD Development System, a programming language using the structure of`C’ language.

¾¾ ARX – AutoCAD Runtime Extension brings in the phenomena of OOPS in to AutoCADenvironment. This is possible because of the C++ interface with AutoCAD. This increasesthe power of AutoCAD many times. Using ARX you can develop your own applicationwhich can have its own objects. (AutoCAD itself is a C++ application)

Page 49: 2_Programming in AutoLISP

��

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 touse those functions to load, unload and execute them.

The functions dealt in this chapter are as listed below,

xload xunload ads

arx arxload autoarxload

Autoload autoxload autozrxload

xloadLoads an ADS application

(xload <adds application> [<on failure>])

This function load an <ads application>. If the application is successfully loaded then thisreturns the application name or returns a standard error message otherwise. However, if the <onfailure> argument is supplied then the function returns the value of this argument upon failureinstead of an error message.

This function fails to load if the application is already loaded.

Example

(xload “/myappx/xapp”) if successful, returns “/myappx/xapp”

xunloadUnloads an ADS application

(xunload <application> [<on failure>])

This function unloads an <ADS application> specified. If the application is successfullyunloaded then it returns the application name else returns an error message. The <applicationname> should be entered as it was entered during xload. The directory name can be omitted forthis function. If the xunload application fails it causes an AutoLISP error. However if the <onfailure> argument is supplied the functions the value of this argument <on failure> argument issupplied then the function returns the value of this argument <on failure> instead of issuing anerror message.

Example:

(xunload “ame”) if successful, returns “ame”

adsReturns a list of the currently loaded ADS applications

(ads)

Each ADS application loaded and its path is a quoted string in the list.

arx

Returns a list of the currently loaded ARX applications

Page 50: 2_Programming in AutoLISP

��

(arx)

Each ARX application loaded and its path is a quoted string in the list.

Example

Command: (arx)

(“acadapp.arx” “ geomal.arx” “oleaprof.arx”)

arxloadLoads an ARX application

(arxload <application> [<on failure>])

The <application> argument is entered as a quoted string or as a variable that contains thename of an executable file. At the time the file is loaded, it is verified to be a valid ARXapplication.

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 failureinstead of an error message. If the application is successfully loaded then the application name isreturned.

arxunloadUnloads 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 anapplication that was loaded with the arxload function. The <application> name must be enteredexactly as it was entered for the arxload function. If a path (directory name) or extension wasentered for the application in arxload, it can be omitted in the arxunload function.

autoload

Predefines command names to load an associated AutoLISP file

(autoload <filename> <cmdlist>)

The <filename> argument is a string that specifies the “.lsp” file that is loaded when oneof 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 thecommand prompt the ARX application loads and the command continues.

Example:

(autoload “BOUNSAPP” (“APP1” “APP2” “APP3”))

Page 51: 2_Programming in AutoLISP

��

autoxload

Predefines command names to load an associated ADS application.

(autoxload <filename> <cmdlist>)

The <filename> argument is a string that specifies the ADS file that is loaded when oneof 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 thecommand prompt the ARX application loads and the command continues.Example:

(autoxload “BOUNSAPP” (“APP1” “APP2” “APP3”))

DIALOG CONTROL LANGUAGE [DCL]

AutoCAD gives you a language called as Dialog Control Language (DCL) which has gotits own syntax and functions, using which you could design your dialog box. Autodesk hasprovided two file ACAD.DCL and BASE.DCL in which many of the commonly used dialog boxcomponents, their structure and layout are predefined.

The definition a dialog box is written using Dialog Control Language in separate ASCIIfiles that contain the descriptions of the various elements of the dialog box. The above file shouldhave a file name extension .dcl. A .dcl file can contain the description of a single or multipledialogue boxes. The arrangement of elements (tiles) in a dialog box, such as buttons andedit_boxes, is determined by their order in the .dcl file.

Dialog Box Components

The following figure shows the various components of a Dialog box, In dialog boxcreation these components are called as tiles.The two major components of a dialog box are tilesand the box itself. The tiles can be arranged in any desired format (lime rows or columns). Thebasic tiles, such as buttons, lists, edit boxes, images, toggle, radio button, etc., are predefined bythe programmable dialog box facility of AutoCAD and are defined in BASE.DCL. By groupingthe tiles into rows and columns, it is possible to create complex tiles, called subassembly. Thelayout of the tile and their functionality are controlled by the attributes associated with the tiles.

Page 52: 2_Programming in AutoLISP

��

alignment

alignment = position;

Applied to: all tiles

Specifies the justification of a tile within its cluster. The possible values of a tile inside acolumn 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;

Applied to: image, image_button

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;

Applied to: image, image,button

Specifies the background (fill) color of the image. Possible values are an integer orreserved word (default : 7) specified as an AutoCAD color number or as one of the symbolicnames show in the following table.

Symbolic Name Meaning

Dialog_line Current dialog box line color

Dialog_foreground Current dialog box foreground color (for text)

Dialog_foreground Current dialog box background color

Page 53: 2_Programming in AutoLISP

��

graphics_background Current background of the AutoCAD graphics screen

black AutoCAD color = 0 (black)

red AutoCAD color = 1 (red)

yellow AutoCAD color = 2 (yellow)

green AutoCAD color = 3 (green)

cyan AutoCAD color = 4 (cyan)

blue AutoCAD color = 5 (blue)

magenta AutoCAD color = 6 (magenta)

white graphica_foreground AutoCAD color = 7 (white)(appears black on a lightbackground)

edit_limit

edit_limit = integer;

Applied to: edit_box

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;

Applied to: button

Page 54: 2_Programming in AutoLISP

��

Specifies whether the button is the default selected (“pushed”) when the user presses theaccept (enter) key. Only one button in a dialog box can have the is_default attribute set to true.

is_enabled

is_enabled = true – false;

Applied to: all active tiles

Specifies whether the tile is initially grayed out (unavailable). Possible values are true offalse (default: true). If false, the tile is initially grayed out.

is_tab_stop

is_tab_stop = true – false ;

Applied to: all active tiles

Specifies whether the tile receives keyboard focus when the user moves between tiles bypressing 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” ;

Applied to: all active tiles

Specifies an ASCII name that the program uses to refer to this specific tile. Possible valueis 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 itas check_no. Because the value of a key isn’t visible to the user, its name can be whatever youchoose (as long as it is unique to the dialog box).

Page 55: 2_Programming in AutoLISP

��

label

label = “string”;

Applied to: boxed_row, boxed_column, boxed_ratio_row,

Bosed_radio_column, button, dialog, edit_box, list_box,

Popup_list, radio_button, text, and toggle.

Specifies the text displayed within the tile. Possible value is a quoted string (default: ablank string, “ “ . The placement of label text is tile specific.

If a character in the label string is preceded by an ampersand (&), that character becomesthe mnemonic.

list

list = “string”;

Applied to: list_box, popup_list

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). Tabcharacter (\t) can occur within each line.

mnemonic

mnemonic = “char”;

Applied to: all active tiles

Specifies a keyboard mnemonic character for the tile. The mnemonic is underlined in thetile’s label. Possible value is quoted string of a single character (no default). The character mustbe 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 tilessequentially.

value

Page 56: 2_Programming in AutoLISP

��

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 atile’s value varies depending on the kind of tile. The value of a tile can change at run time, withuser input or set_tile calls.

The value attribute of a tile is not considered when the dialog box is laid out. After thelayout is finished and the dialog box has been displayed, new_dialog uses the value attributes toinitialize each tile in the dialog box. At tile’s value attribute has no effect on the size or spacing oftiles in the dialog box.

width

width = number;

Applied to: all tiles

Specifies the width of a tile. Possible values are an integer or a real number representingthe distance in character-width units. Do not specify this value unless the assigned defaults don’tprovide acceptable appearance. You must specify, however, the width of image tiles and imagebuttons.

big_increment

big_increment = integer;

Applied to: slider

Specifies the value used by the slider’s incremental controls. The default value ofbig_increment is one-tenth of the total range. The value must be within the range specified bymin_value and max_value.

Page 57: 2_Programming in AutoLISP

��

small_increment

small_increment = integer;

Applied to: slider

Specifies the value by the slider’s incremental controls. Default value of small_incrementis one one-hundredth the total range. The value must be within the range specified by min_valueand max_value. This attribute is optional.

layout

layout = position;

Applied to: slider

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, itincreases from button to top.

Password_char

Password_char = “cahr”;

Applied to: edit_box

Specifies the character to be used as the password character. If password_char isspecified and is not null, that character is displayed in the edit box instead of the charactersentered by the user. The use of this attribute has no effect on the retrieval of the value entered bythe user. It alters only the display of the characters in the edit box.

DCL Tile Catalog

Having seen the attributes which control the properties of the tiles, let us now have adetailed look at the various Tiles available and how to use them,

dialog: dialog {

Page 58: 2_Programming in AutoLISP

��

initial_focus label value

}

A dialog is the tile that defines the dialog box. You should not specify both a label and valueattribute: the value attributes that of the label.

label :Specifies the optional tile displayed in the tile bar.

initial_focus :Specifies the key of the tile that receives the initial keyboardfocus.

initial_focus :Specifies the key of the tile that receives the initial keyboardfocus.

Example:

To create a dialog shown,

: dialog {

label = “You did it . . . “;

ok_only;

}

button:button {

alignment fixed_height fixed_width height is_cancel is_default is_enabled is_tab_stopkey label mnemonic width

}

A button tile resembles a push button. The button’s label specifies text that appears insidethe button.

Dialog boxes must include an OK button (or its equivalent) for the user to press afterusing (or reading) the box. Many dialog boxes also include a Cancel button that enablesthe user to leave the dialog box without making any changes.

Example

Page 59: 2_Programming in AutoLISP

��

:button {

label = “Execute”;

fixed_height = true;

fixed_width = true;

edit box:edit_box{

alignment edit_limit edit_width fixed_height fixed_width height is_enabledis_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. Anoptional label can appear to the left of the box. If the entered text is longer thanthe length of the edit box, its scrolls horizontally.

Image:image {

alignment aspect_ratio color fixed_height fixed_width height is_enabledis_tab_stop key label mnemonic value width

}

An image is a rectangle in which a vector graphic picture is displayed. You can use animage 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”;

}

Page 60: 2_Programming in AutoLISP

��

list_box:list_box{

alignment fixed_height fixed_width height is_enabled is_tab_stop key label listmnemonic value width

}

Example:

: list_box

height = 10;

width = 10;

key = “lis”;

}

popup_list:popup_list {

alignment edit_width fixed_height fixed_width height is_enabled is_tap_stop keylabel list mnemonic value width

}

radio_button: radio_button {

alignment fixed_height fixed_width height is_enabled is_tab_stop key labelmnemonic 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.

Page 61: 2_Programming in AutoLISP

��

Example:

:radio_button {

label = “Left”;

mnemonic = “L”;

key = “left”;

}

texttext {

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

If it is “1”, the box contains a check mark (or an X).

slider:slider {

action alignment big_increment fixed_height fixed_width height key label layoutmax_value min_value mnemonic small_increment value width

ok_onlyok_only;

Page 62: 2_Programming in AutoLISP

��

The ok_only tile is solitary OK button, such as the kind that alert boxes use. Thekey of the OK button is “accept”.

The ok_only tile is defined in the base.dcl file.

ok_cancel

ok_cancel;

The ok_cancel tile is a combination of the OK and Cancel buttons, and is the standardcombination for dialog boxes that can originate changes to data. The key of the Cancelbutton is “cancel”.

The of_cancel tile is defined in the base.dcl file.

errtileerrtile;

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

The errtile tile is defined in the base.dcl file.

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 rowsand other columns.

A column without a box has no additional attributes beyond the standard layoutattributes.

Page 63: 2_Programming in AutoLISP

��

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 islaid inside will be in a column fashion. If a boxed_column has a label, the label (title) isembedden 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 onefunction. It encloses the radio_buttons in a column, at a point of time only one radiobutton can be selected. You treat the label the same way that you would treat the label ofa boxed column.

radio_column:radio_column {

alignment fixed_height fixed_width height width

}

A set of radio buttons arranged in a column.

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 theorder in which appear in the DCL file.

A row without a box has no additional attributes beyond the standard layout attributes.

Page 64: 2_Programming in AutoLISP

��

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 appearsembedded 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 youwould 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

}

A set of radio button arranged in a row.

SAMPLE PROGRAMS

This section gives you some sample DCL files. Try these first before creating anyDialogs of your own on the exercises, and clearly understand each and every line in theseprograms. Follow the instructions given.

Example: 01

/* this is a comment. . . .

A sample dialog which appears as shown in the figure. . .

Page 65: 2_Programming in AutoLISP

��

The dialog name is mydial, and the coding is written in great.dcl. . .

*/

mydial:dialog {

label = “This is my first dialog box”; //heading of dialog

:text {

label = “Great ! You’ve done it. . . “;//text tile

}

ok_only;

} / / dialog ends here

load_dialog

(load_dialog <dcl_file>

The dcl_file argument is a string that specifies the .dcl file to load. Returns a positiveinteger 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.

This function is the complement of unload_dialog.

Example:

(setq dcl_id (load_dialog “great.dcl”) ) returns 1

new_dialog

(new_dialog <dlg name> <dcl_id>

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:

(new_dialog “mydial” dcl_id) displays the dialog on screen

Page 66: 2_Programming in AutoLISP

��

Page 67: 2_Programming in AutoLISP

��

FILE HANDLING

Every engineering design process, irrespective of the trade, whether Mechanical, Civil orArchitectural, needs data. These data are standards and thumb rules for an optimum designsolution. In conventional design process, an engineer has to repeatedly refer volumes ofcatalogs, tables and charts which is a tedious process.

In the modern world, where computers are used to aid in the design process, one neednot look the design data table. All the necessary data can be stored as data files and the designprogram 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 orthrough 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.

The functions included in this chapter are as listed below.

The functions included in this chapter are,

findfile open close

read-line write-line read-char

write-char getfiled

findfile

Searches the AutoCAD library path for the specified file

findfile <file name>)

Returns:

If the file is found Path of file as a STRING

If the file is not found nil

The FINDFILE function searches for the given file whose name is given as the stringargument in the AutoCAD library path. The file name should also include the extension of thefile. If the drive or directory prefix is given then the file is searched only in the specified drive ordirectory.

Page 68: 2_Programming in AutoLISP

��

Example:

If there is a file named “shaft.lsp” in the path c:\acadr14,then,

Command: (findfile “shaft.lsp”)

“C:\\ACADR14\\shaft.lsp”otherwise,

Command: (findfile “shaft.lsp”)

Nil

Open

Opens a file for access by the AutoLISP I/O functions

(open <filename> <mode>

Returns:

If the file is found File Pointer (descriptor)

If the file is not found nil

The filename argument is a string that specifies the name and extension of the file to beopened. The mode argument is the read/write flag. It must be a string containing a single lowercase letter. The following table describes the valid mode letters.

Open mode Description

“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. Iffilename already exists, Its existing data is overwritten.

“a” Open for appending. If filename does not exit, a new file is created a new file iscreated and opened. If filename already exists, it is opened and the pointer ispositioned at the end of the existing data, so new data you write to the file isappended to the existing data.

Open function returns a file description to be used by the other I/O functions. The filedescriptor must be assigned to a symbol that uses the seta function as shown below. All furtherreference to the file should be through the file descriptor.

Page 69: 2_Programming in AutoLISP

��

Example

Assuming that the files named in the following examples do not exit,

Command: (setq f (open “new.txt” “w”)

<File: # 22712c6>Command: (setq f(open “nosuch.fil” “r”))nilCommand: (setq f (open “lofgile” “a”))<File: # 22711d8>

When a file “data.txt” exists,

Command: (setq f (open “data.txt” “r”))<File: # 227115a>

Close

Closes an open file

(close <file descriptor>)

Returns

on success nil

on failure error message

The <file descriptor> argument is a file descriptor obtained from the open function. Aftera close, the file descriptor is unchanged but is no longer valid. All files opened in a programhave 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 variableno_lines equal to that number:

(setq fil_id(open “check.txt” “r”) no_lines 0)(while (read-linefil_id) (setq no_lines ( 1 + no_lines)))(close fil_id)

read – char

Returns the ASCII code of the character read from an open file or from keyboard.

(read-char [<file descriptor>])

Returns

on success nil

Page 70: 2_Programming in AutoLISP

��

on failure error message

This function returns the decimal ASCII code representing the character read from thekeyboard input buffer or from an open file described by the <file descriptor>. If there are no <filedescriptor>s and characters in the keyboard input buffer, the function waits for a keyboard input.

Example

Command: (setq f (open “data.txt” “r”))<file: # 227115a>Command: (read-char f)106

write – char

Writes a character to the screen or to an open file

(write – char <num> [<file descriptor>])

Returns

on success write the character

on failure error message

This function writes a character to the screen or to an open file. The <num> argument isa decimal ASCII code for the character specified by the <num>. If no <file descriptor> is giventhen the character is written on the screen else the character will be written to the specified file.

Example

Command: (write – char 65)A

Command: setq fp O(open “data.txt” “a” ))<File: # 22713fa>Command: (write – char 65 fp)

The last example writes character A onto the open file whose <file descriptor> is fp. Ineither case, WRITE – CHAR will echo the argument (65 in this case) at the Command: prompt

read – line

Reads a string from the keyboard or from an open file.

(read – line [<file descriptor>])

Returns

Page 71: 2_Programming in AutoLISP

��

on success line read as string

on failure nil

This function returns the line read from the keyboard or from an open file. When thisfunction is repeated with the file descriptor then the function returns the next line of the file.

Example

Assuming that fp is a valid open file pointer,

(read-line fp)

returns the next input line from the file, or returns nil if the end-of-file has been reached.

write – line

Writes a string to the screen or to an open file

(write – line <string> [<file descriptor>])

Returns:on success string omitting the quotes

on failure error messageThis function write the <string> to the screen or to an open file. The function returns a

quoted string to the file if <file descriptor> is specified. Otherwise the <string> is written on thescreen

Example

Assuming that fp is a valid open file descriptor.

(write – line “Welcome” fp)

writes Welcome in the file.

getfiled

Display the standard AutoCAD file dialog box, and returns that the name

(getfiled <title> <default> <ext> <flags>)

Returns

If file is selected the file selected as string

If file not selected nil

Page 72: 2_Programming in AutoLISP

��

The <title> argument specifies the dialog box label. The <default> arguments specifies adefault file name to use for the dialog box. It can be empty string also. The <ext> argumentspecifies the default file name extension, used as a mask for the files presented to the user in ascrolling list box. This function returns the name of the selected by the user, or nil if no file wasselected. The <flags> argument is an integer value ( a bit-coded field), the meaning of thevarious bit values are:

Bit Value Meaning

1. Display “alert” message if the user selects an existing file.2. Disables the “Type It” button in the dialog box.4. Allows the user to change the file extension or no extension at all.8. Performs an AutoCAD library search for the filename entered.

Example:

Command: (getfiled “Select a Lisp File” “c:\acadr14” “lsp” 8)“C:\\ACADR14\\Surf.lsp”

If you choose a file from the dialog box and click on OK then AutoCAD returns theselected lisp file name.

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 justbeen added with the command function. The entity need not be on the screen or on a thawedlayer to be selected.

Example:

(setq e1 (entlast))

Sets e1 to the name of the last drawn entity in the drawing.

entnext

Returns the name of the next object (entityO in the drawing.

(entnext [<ename>])

Returns:

if next entity is found The Entity name of the entity

Page 73: 2_Programming in AutoLISP

��

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 returnsthe name of the seceding entity specified by <ename>.

Example

(setq e1 (entnext))

returns the entity name of the first entity in the drawing.

(setq e2 (entnext e1))

returns the entity name of the entity following e1.

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.

Entity not found nil

This function is used to select an entity by specifying a point. The function returns a listcontaining entity name and the point selected. When the optional argument <prompt> isspecified, 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 commandprompt are:

Example:Assuming if there is an object passing through point 3,3Command: (entsel “Pick entity:”)

Pick entity: 3,3

(<Entity name: Ce74h3> (3.000000 3.000000 0.0))

nentsel

Prompts the user to select an object (entity) by specifying a point, and provides access to thedefinition data contained within a complex object.

(nentsel [<prompt>])

Returns

Page 74: 2_Programming in AutoLISP

��

Entity found at point picked The Entity name and the point picked as a list

Entity not found nil

This function provides access to the entities contained inside a nested entity. (such asPOLYLINES and INSERTS) If the optional argument <prompt> is passed then this functionwaits for user selection by issuing <prompt> or else a standard prompt Select Object: will beissued. If the selected objet is not a nested entity (i.e. neither a POLYLINE nor a BLOCKINSERT) then this function returns same information as ENTSELF function. When a sub entityof 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 secondelement will be the point of selection, third one will be a matrix called `Model to WorldTransformation Matrix’ which specifies the location of the sub entity with respect to the insertionpoint of the block. The fourth member of the above list will be entity name of the block thatcontains the selected sub entity.

If the selected entity is an ATTRIBUTE of an INSERT then this function returns only theentity name of the attribute and the pick point.

The nentsel function will be a list as follows:

(<Entity name: ename1> Name of entity(Px Py Pz) Pick point((X0 Y0 Z0)(X1 Y1 Z1) Model to World transformation matrix(X2 Y2 Z2)(X3 Y3 Z))(<Entity name: ename2> Name of most deeply nested block containing selectedentity

<Entity name: ename>) Name of outermost block containing selected entity.)

entupd

Updates the screen image of an object (entity)

(entupd <ename>)

Returns

on success The Entity name

When a polyline vertex or block attribute is modified with entmod, the entire complex entity isnot updated on the screen. The entupd function can be used to cause a modified polyline or block to beupdated on the screen. This function can be called with the entity name of any part of the polyline orblock; it need not be the head entity. While entupd is intended for polylines and blocks with attributes, itcan be called for any entity. It always regenerates the entity on the screen, including all subentities.

Page 75: 2_Programming in AutoLISP

��

Example

Assuming that the first entity in the drawing is a polyline with spline fit data and withseveral vertices, then

(setq e1 (entnext)) ;Sets e1 to the polyline’s entity name(setq e2 (entnext)) ;Sets e2 to its first vertex(setq en (entget)) ;Sets en to the vertex data(setq ed ;Changes the vertex’s location in en to point(subt (`10 1.0.2.0) ;(1,2)

assoc 10 en) en))

(entmod en) ;Moves the vertex in the drawing(entupd e1) ;Regenerates the polyline entity e1

entmod

Modifies the definition data of an object (entity)

Entmod <elist>)

Returns

on success The Entity list

on failure error message (mostly Bad entmod list).

This function modifies the database of the entity specified by <elist>. The <elist> is theassociative list of the entity obtained by entget function.

Example

(command “line “ “2,3” “4,5” “ “)(setq en (entnext)

e1 (entget en) ; gets the entity list of the line.

e1(subst (cons 10 (list 4 4))(assoc 10 e1)e1)) ;changes the starting point of the line to 4,4

(entmod e1) ;updates the database

Page 76: 2_Programming in AutoLISP

��

entdel

Deletes objects (entities) or undeletes previously deleted objects.

(entdel <ename>)

Returns

on success The Entity name

on failure error message (bad argument type)

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

If `b’ is not a valid entity name

Command: (entdel b)Error: bad argument type(ENTDEL B)*Cancel*

entmake

Creates a new entity (graphical object) in the drawing

(entmake <elist>)

Returns

on success The Entity

on failure error message (bad entmake list value)

This function creates a new entity in the current drawing making use of the entity listspecified by <elist> as the definition data. If successful then this returns the definition data andnil otherwise.

Page 77: 2_Programming in AutoLISP

��

The minimum data <elist> for making an entity are as follows:

1. Entity type

2. Basic geometric data

3. Optional arguments

a. Colorb. Layerc. Linetyped. Extrusion directione. Elevationf. Thickness

1. Valid entity types are “LINE”, CIRCLE”, “ARC”, etc.,

2. Geometric data for:

LINE: Start point & End point

CIRCLE: Center point & Radius

SSGET FILTERS

(ssget “X” <filter list>

This function selects all the entities conforming to a specified filter list. The <filter list> isan 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 type2 Block name of block references6 Line type name7 Text style name for text and attribute definitions8 Layer name38 Elevation (real)39 Thickness (real)62 color number (0 => “BYBLOCK”

256 = > “BYLAYER”)66 Attributes – follow flag for block references210 3D extrusion direction vector (list of three reals).

Example:

(ssget “X” (list (cons 0 “line”))) ;selects all lines(ssget “X” (list cons 0 “line”)

Page 78: 2_Programming in AutoLISP

��

(cons 8 “C”))) ;selects all lines in the layer named C

sslength

Returns an integer containing the number of objects (entities) in selection set

(sslength) <ss>)

Returns

on success no of entity names present in the set

on failure error message

The number is returned as a real if it is greater than 32, 767. Selection sets nevercontain 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>. Itreturns 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.

(set1 e1 (ssname sd0)) ;selects the first entity in the;selection set sd.

(ssdel e1 sd) ;deletes the lines e1 from the set sd.

sssetfirst

Sets which objects are selected and gripped

(sssetfirst <gripset> [pickset>])

Page 79: 2_Programming in AutoLISP

��

Returns

on success list of the variables passed

on failure error message

Example

The expressions below grips all the entities in the drawing

Command: (setq a (ssget “x”))<Selection set:1>Command: (sssetfirst a)(A)

ssgetfirst

Determines which objects are selected and gripped(ssgetfirst

Returns

on success list of the selection sets (gripped / selected)

on failure error message

Example

Command: (ssgetfirst)[<Selection set: 2> nil)

APPLICATION HANDLING

Almost all environments and software provide the user the tools to develop applications forhis/her need through customization. It is appropriate because it is very difficult or rather impractical togroup all the needs of the user by software developer himself. In this context, understanding theimportance and the advantages of customization, Autodesk has developed AutoCAD with an openarchitecture, which encourages customizing to a large extent.

Autodesk has considered both the noise and experienced user has given tools for various levelsof customization. It depends on the knowledge and experience of the user, in AutoCAD as well as otherprogramming language such as AutoLISP and C. It is also based on the nature and complexity of theapplication to the developed.

Page 80: 2_Programming in AutoLISP

��

AutoCAD can be customized through,

¾¾ AutoLISP, a programming language framed by the Autodesk for developing small applicationsinvolving either designing or drafting in AutoCAD.

¾¾ ADS – AutoCAD Development System, a programming language using the structure of `C’language.

¾¾ ARX – AutoCAD Runtime Extension brings in the phenomena of OOPS in to AutoCADenvironment. This is possible because of the C++ interface with AutoCAD. This increases thepower of AutoCAD many times. Using ARX you can develop your own application which canhave its own objects. (AutoCAD itself is a C++ application)

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 thosefunctions to load, unload and execute them.

The functions dealt in this chapter are as listed below,

xload xunload ads

arx arxload autoarxload

Autoload autoxload autozrxload

xload

Loads an ADS application

(xload <adds application> [<on failure>])

This function load an <ads application>. If the application is successfully loaded then this returnsthe 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 errormessage.

Page 81: 2_Programming in AutoLISP

��

This function fails to load if the application is already loaded.

Example

(xload “/myappx/xapp”) if successful, returns “/myappx/xapp”

xunload

Unloads an ADS application

(xunload <application> [<on failure>])

This function unloads an <ADS application> specified. If the application is successfully unloadedthen it returns the application name else returns an error message. The <application name> should beentered as it was entered during xload. The directory name can be omitted for this function. If the xunloadapplication fails it causes an AutoLISP error. However if the <on failure> argument is supplied thefunctions the value of this argument <on failure> argument is supplied then the function returns the valueof this argument <on failure> instead of issuing an error message.

Example:

(xunload “ame”) if successful, returns “ame”

ads

Returns a list of the currently loaded ADS applications

(ads)

Each ADS application loaded and its path is a quoted string in the list.

arx

Returns a list of the currently loaded ARX applications

Page 82: 2_Programming in AutoLISP

��

(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 nameof 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 <onfailure> argument is supplied then arxload returns the value of this argument upon failure instead of anerror 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 thatwas loaded with the arxload function. The <application> name must be entered exactly as it was enteredfor 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.

Page 83: 2_Programming in AutoLISP

��

autoload

Predefines command names to load an associated AutoLISP file

(autoload <filename> <cmdlist>)

The <filename> argument is a string that specifies the “.lsp” file that is loaded when one of thecommand 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 commandprompt the ARX application loads and the command continues.

Example:

(autoload “BOUNSAPP” (“APP1” “APP2” “APP3”))

autoxload

Predefines command names to load an associated ADS application.

(autoxload <filename> <cmdlist>)

The <filename> argument is a string that specifies the ADS file that is loaded when one of thecommands 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 commandprompt the ARX application loads and the command continues.

Example:

(autoxload “BOUNSAPP” (“APP1” “APP2” “APP3”))

Page 84: 2_Programming in AutoLISP

��

DIALOG CONTROL LANGUAGE [DCL]

AutoCAD gives you a language called as Dialog Control Language (DCL) which has got its ownsyntax and functions, using which you could design your dialog box. Autodesk has provided two fileACAD.DCL and BASE.DCL in which many of the commonly used dialog box components, theirstructure and layout are predefined.

The definition a dialog box is written using Dialog Control Language in separate ASCII files thatcontain the descriptions of the various elements of the dialog box. The above file should have a file nameextension .dcl. A .dcl file can contain the description of a single or multiple dialogue boxes. Thearrangement of elements (tiles) in a dialog box, such as buttons and edit_boxes, is determined by theirorder in the .dcl file.

Dialog Box Components

The following figure shows the various components of a Dialog box, In dialog box creation thesecomponents are called as tiles.

Page 85: 2_Programming in AutoLISP

��

The two major components of a dialog box are tiles and the box itself. The tiles can be arranged in anydesired 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 inBASE.DCL. By grouping the tiles into rows and columns, it is possible to create complex tiles, calledsubassembly. The layout of the tile and their functionality are controlled by the attributes associated withthe 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 columnare left, right or centered (default : left), the possible values of a tile inside a row are top, bottom, orcentered (default : centered).

aspects_ratio

aspect_ratio = real;

Applied to: image, image_button

Specifies the ratio of the width of the image to its height (width divided by height). Possiblevalues are floating-point values (default : none).

Color

Color = colorname;

Applied to: image, image,button

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

Symbolic Name Meaning

Dialog_line Current dialog box line color

Page 86: 2_Programming in AutoLISP

��

Dialog_foreground Current dialog box foreground color (for text)

Dialog_foreground Current dialog box background color

graphics_background Current background of the AutoCAD graphics screen

black AutoCAD color = 0 (black)

red AutoCAD color = 1 (red)

yellow AutoCAD color = 2 (yellow)

green AutoCAD color = 3 (green)

cyan AutoCAD color = 4 (cyan)

blue AutoCAD color = 5 (blue)

magenta AutoCAD color = 6 (magenta)

white graphica_foreground AutoCAD color = 7 (white)(appears black on a light background)

edit_limit

edit_limit = integer;

Applied to: edit_box

Specifies the maximum no of characters a user is allowed to enter in the edit_box. Possible valuesin an integer (default : 132). The maximum edit_limit allowed is 256 characters.

is_default

Page 87: 2_Programming in AutoLISP

��

is_default = true – false;

Applied to: button

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

is_enabled = true – false;

Applied to: all active tiles

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

is_tab_stop = true – false ;

Applied to: all active tiles

Specifies whether the tile receives keyboard focus when the user moves between tiles by pressingthe 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 tabstop.

key

key = “string” ;

Applied to: all active tiles

Specifies an ASCII name that the program uses to refer to this specific tile. Possible value is aquoted string (no default). Within a particular dialog box, each key value must be unique. This string iscase sensitive: if you specify the key as Check_no BigTile, you cannot reference it as check_no. Because

Page 88: 2_Programming in AutoLISP

��

the value of a key isn’t visible to the user, its name can be whatever you choose (as long as it is unique tothe dialog box).

label

label = “string”;

Applied to: boxed_row, boxed_column, boxed_ratio_row,

Bosed_radio_column, button, dialog, edit_box, list_box,

Popup_list, radio_button, text, and toggle.

Specifies the text displayed within the tile. Possible value is a quoted string (default: a blankstring, “ “ . The placement of label text is tile specific.

If a character in the label string is preceded by an ampersand (&), that character becomes themnemonic.

list

list = “string”;

Applied to: list_box, popup_list

Specifies the initial set of lines (choices) to be placed in the popup_list or list_box. Possible valueis a quoted string (no default). Lines are separated by a new line symbol (\n). Tab character (\t) can occurwithin each line.

mnemonic

mnemonic = “char”;

Applied to: all active tiles

Specifies a keyboard mnemonic character for the tile. The mnemonic is underlined in the tile’slabel. Possible value is quoted string of a single character (no default). The character must be one of theletters in the tile’s label. The character doesn’t have to be unique to the dialog box: if more than one tilehas the same mnemonic, the user presses that key to cycle through the tiles sequentially.

Page 89: 2_Programming in AutoLISP

��

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 valuevaries depending on the kind of tile. The value of a tile can change at run time, with user input or set_tilecalls.

The value attribute of a tile is not considered when the dialog box is laid out. After the layout isfinished and the dialog box has been displayed, new_dialog uses the value attributes to initialize each tilein 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;

Applied to: all tiles

Specifies the width of a tile. Possible values are an integer or a real number representing thedistance in character-width units. Do not specify this value unless the assigned defaults don’t provideacceptable appearance. You must specify, however, the width of image tiles and image buttons.

big_increment

big_increment = integer;

Applied to: slider

Specifies the value used by the slider’s incremental controls. The default value of big_incrementis 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;

Page 90: 2_Programming in AutoLISP

��

Applied to: slider

Specifies the value by the slider’s incremental controls. Default value of small_increment is oneone-hundredth the total range. The value must be within the range specified by min_value andmax_value. This attribute is optional.

layout

layout = position;

Applied to: slider

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

Password_char

Password_char = “cahr”;

Applied to: edit_box

Specifies the character to be used as the password character. If password_char is specified and isnot null, that character is displayed in the edit box instead of the characters entered by the user. The use ofthis attribute has no effect on the retrieval of the value entered by the user. It alters only the display of thecharacters in the edit box Having seen the attributes which control the properties of the tiles, let usnow have a detailed look at the various Tiles available and how to use them,

dialog

Page 91: 2_Programming in AutoLISP

��

: 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: thevalue attributes that of the label.

label :Specifies the optional tile displayed in the tile bar.

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:

To create a dialog shown,

: dialog {

label = “You did it . . . “;

ok_only;

}

button

:button {

alignment fixed_height fixed_width height is_cancel is_default is_enabled is_tab_stop key labelmnemonic width

}

A button tile resembles a push button. The button’s label specifies text that appears inside thebutton.

Dialog boxes must include an OK button (or its equivalent) for the user to press after using (orreading) the box. Many dialog boxes also include a Cancel button that enables the user to leavethe dialog box without making any changes.

Page 92: 2_Programming in AutoLISP

��

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_stopkey 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. Anoptional label can appear to the left of the box. If the entered text is longer than the lengthof the edit box, its scrolls horizontally.

Image

:image {

alignment aspect_ratio color fixed_height fixed_width height is_enabled is_tab_stop keylabel mnemonic value width

}

Page 93: 2_Programming in AutoLISP

��

An image is a rectangle in which a vector graphic picture is displayed. You can use an image todisplay 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 listmnemonic value width

}

Example:

: list_box

height = 10;

width = 10;

key = “lis”;

}

Page 94: 2_Programming in AutoLISP

��

popup_list

:popup_list {

alignment edit_width fixed_height fixed_width height is_enabled is_tap_stop key labellist mnemonic value width

}

radio_button

: radio_button {

alignment fixed_height fixed_width height is_enabled is_tab_stop key label mnemonicvalue width

}

Value: A quoted string (no default). If the value is “1”, the radio_button is on; if it is “0”, theradio_buttons is off.

Example:

:radio_button {

label = “Left”;

mnemonic = “L”;

key = “left”;

}

text

text {

alignment fixed-height fixed_width height key label value width

}

Page 95: 2_Programming in AutoLISP

��

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

If it is “1”, the box contains a check mark (or an X).

slider

:slider {

action alignment big_increment fixed_height fixed_width height key label layoutmax_value min_value mnemonic small_increment value width

ok_only

ok_only;

Page 96: 2_Programming in AutoLISP

��

The ok_only tile is solitary OK button, such as the kind that alert boxes use. The key ofthe OK button is “accept”.

The ok_only tile is defined in the base.dcl file.

ok_cancel

ok_cancel;

The ok_cancel tile is a combination of the OK and Cancel buttons, and is the standardcombination for dialog boxes that can originate changes to data. The key of the Cancel button is“cancel”.

The of_cancel tile is defined in the base.dcl file.

errtile

errtile;

An error tile is a text tile that appears at the bottom of a dialog box. By default it’s blank, putprograms can display messages in it by setting the value of the tile whose key is “error”.

The errtile tile is defined in the base.dcl file.

Page 97: 2_Programming in AutoLISP

��

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. Acolumn can contain any kind of tile (except for solitary radio buttons), including rows and othercolumns.

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 laidinside will be in a column fashion. If a boxed_column has a label, the label (title) is embedden init on the top left corner of the box.

boxed_radio_column

:bosed_radio_column {

alignment fixed_height fixed_width height label width

Page 98: 2_Programming in AutoLISP

��

}

A boxed_radio_column is very similar to the boxed_column in all means except one function. Itencloses 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

}

A set of radio buttons arranged in a column.

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 inwhich appear in the DCL file.

A row without a box has no additional attributes beyond the standard layout attributes.

boxed_row

Page 99: 2_Programming in AutoLISP

��

: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 treatthe label of a boxed row.

At any point of time only one radio_button can be selected indicating the option needed.

Page 100: 2_Programming in AutoLISP

��

radio_row

:boxed_radio_row{

alignment fixed_height fixed_width height label width

}

A set of radio button arranged in a row.

SAMPLE PROGRAMS

This section gives you some sample DCL files. Try these first before creating any Dialogs of yourown on the exercises, and clearly understand each and every line in these programs. Follow theinstructions given.

Example: 01

/* this is a comment. . . .

A sample dialog which appears as shown in the figure. . .

The dialog name is mydial, and the coding is written in great.dcl. . .

*/

mydial:dialog {

label = “This is my first dialog box”; //heading of dialog

:text {

label = “Great ! You’ve done it. . . “;//text tile

}

ok_only;

} / / dialog ends here

Page 101: 2_Programming in AutoLISP

��

load_dialog

(load_dialog <dcl_file>

The dcl_file argument is a string that specifies the .dcl file to load. Returns a positive integervalue (dcl_id) if successful, and returns a negative integer if it can’t open the file. The dcl_id isused as a handle in subsequent new_dialog and unload_dialog calls.

This function is the complement of unload_dialog.

Example:

(setq dcl_id (load_dialog “great.dcl”) ) returns 1

new_dialog

(new_dialog <dlg name> <dcl_id>

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:

(new_dialog “mydial” dcl_id) displays the dialog on screen

Page 102: 2_Programming in AutoLISP

��

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 throughADS using ADS_invoke ().

Return values for the API

The AutoCAD Render API commands have three different return values that calling application can useto determine if the command is successful1. IF the command fails, the function returns nil in AutoLisp or a NULL result buffer pointer in ADS2. If the command is successful, and the command returns explicit values, it returns a value like .033. 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 anexisting finish.

(c: finish mode [options])

The FINISH command has EIGHT modes1 “N” Create New FinishSYNTAX: - (c: finish “N” name [ka [kd [ks [roughness [color]]]]])

2 “M” Modify existing finishSYNTAX: - (c: finish “M” name [ka [kd [ks [roughness [color]]]]])

3 “D” Delete existing finishSYNTAX: - (c: finish “D” name)

4 “R” Rename existing finishSYNTAX: - (c: finish “R” old_name new_name)

5 “I” Import existing finishSYNTAX: - (c: finish “I” name [overwrite])

6 “E” Export existing finishSYNTAX: - (c: finish “E” name [overwrite])7 “A” Attach existing finish to finish to entity or ACISYNTAX: - (c: finish “A” name [ACI]| [SELECTION_SET])

8 “L” List all finishes in the drawing or return a definition of the specified finishSYNTAX: - (c: finish “L” name)

Page 103: 2_Programming in AutoLISP

��

The FINISH command has following options

OPTION DESCRIPTION DEFAULT

NAME Unique finish name None

Ka Ambient factor .30

Kd Diffuse factor .70

Ks Specular factor .00

Roughness Roughness factor .10

Color Any RGB triplet Entity ACI

Overwrite Replace definition None

ACI AutoCAD color Index None

Selection Set Entities attached None

LIGHT Command

The LIGHT command lets you add a new light, and modify or delete an existing light.

(c: light mode [option])

This command is not allowed in paper space

The LIGHT command has NINE modes

1 “ND” New distant lightSYNTEX: - (c: light “ND” name [intensity])

2 “NP” New point lightSYNTEX: - (c: light “NP” name [intensity])

3 “NS” New spotlightSYNTEX: - (c: light “NS” name [intensity])

4 “A” Set ambient light intensitySYNTEX: - (c: light “A” [intensity])

5 “F” Set point light falloffSYNTEX: - (c: light “F” [Falloff])

6 “M” Modify existing lightSYNTEX: - (c: light “M” name)

Page 104: 2_Programming in AutoLISP

���

7 “D” Delete existing lightSYNTEX: - (c: light “D” name )

8 “R” Rename an existing lightSYNTEX: - (c: light “R” name)

9 “L” List all lights in the drawing or return a definition of the specified lightSYNTEX: - (c: light “L” name)

OPTION DESCRIPTION DEFAULT

Name Unique finish name none

Intensity Any positive real number or nil 1.00

Fall-off Point light fall-off . 1

From Light location Current look-from point

To Light target Current look-from point

Color Any RGB triplet 1.0,1.0,1.0

Depthmap Valid values are 0 to 6 0

Conea cone angle in degree (spot light) 10

Coned cone delta in degrees (spot light)0

Beamed Beam distribution (spot light) 0

RCONFIG Command

The RCONFIG command reconfigures your current rendering setup. Use following syntax:(c: rconfig )

RENDER Command

The RENDER command renders the current scene.(c: render)

RENDSCR Command

The RENDSCR command redisplays your last rendering

(c: rendscr )

Page 105: 2_Programming in AutoLISP

���

REPLAY Command

The REPLAY command lets you display RND, TGA, TIFF, or GIF files on the AutoCAD renderingdisplay

(c: replay filename type [xoff yoff xsize ysize ])

The following table shows the REPLAY argument list.

OPTION DESCRIPTION DEFAULT

File-name Unique image filename None

Type Valid values are: GIF, TGA, NoneTIFF, or RND

Xoff Image X offset in pixels 0

Yoff Image Y offset in pixels 0

Xsize Image X size pixels Image X size

Ysize Image y size pixels Image Y size

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

(c: rpref keyword [options ])

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

when configured to render to a separate display,use the following syntax

(c: saveimg filename type [xoff yoff xsize ysize] [ compression ] )

Page 106: 2_Programming in AutoLISP

���

OPTION DESCRIPTION DEFAULT

File-name Unique image filename None

Type Valid values are : GIF,TGA, NoneTIFF, or RND

Portion Portion of the screen to save. “A”Valid values are:“A” (Active viewport)“D” (Drawing viewport)“F” (Full screen)

Xoff Image X offset in pixels 0

Yoff Image Y offset in pixels 0

Xsize Image X size pixels Image X size

Ysize Image y size pixels Image Y size

Compression Valid values are NONE, RLEPACK, LZW& RLE

SCENE Command

A scene represents a particular view of any portion of the drawing including the whole drawing, togetherwith one or more lights . The SCENE command lets you create a new scene , or delete and modify anexisting scene .

(c: scene mode [options ] )

THE SCENE COMMAND has following modes

1 “N” Creates new sceneSYNTAX: - (c: scene “N” name [view [lights ] ] )

2 “M” Modifies existing sceneSYNTAX: - (c: scene “M” name [view [lights ] ] )

3 “D” Deletes existing sceneSYNTAX: - (c: scene “D” name )

4 “R” Rename existing sceneSYNTAX: - (c: scene “R” old_name new_name)

5 “S” Sets current sceneSYNTAX: - (c: scene “S” [ name ] )

6 “L” Lists all scenes in the drawing or return a definition of the specified scene

Page 107: 2_Programming in AutoLISP

���

SYNTAX: - (c: scene “L” name )

STSTS Command

The STATS command provides information about your last rendering

( c: stats [filename ] )

AutoCAD SQL interface

The AutoCAD SQL Interface (ASI ) is programming library for accessing external databases fromAutoCAD . The AutoCAD SQL Extension user command set is an ADS application build with ASI.ASI lets you access external database directly from AutoCAD using library unction supplied withAutoCAD. ASI can provide simultaneous access to different database management systems from thesame program. The ASI interface consists of two levels. The first level is driver that communicates with theDBMS or with the database directly. The second level is a driver-independent library of functions that cancommunicate with any driver. The main purpose of library is to handle communications between theapplication program and multiple drivers. The driver performs syntax checking and execution of all theSQL statements passed to it from the library.Drivers include with the ASI are Dbase IV, DBASE III PLUS, INFORMIX, ORCALE, and PARADOX

ASI Files and Their Contents

ASI includes these files

1. ASI Object LibraryASI has three-object library

1. asiph.lib for the MetaWare compiler2. asipw.lib for the WATCOM compiler3. asi.a for the SPARC compiler

2. ASI Header FilesASI has two header files

1. asi.h containing general-purpose definitions for ASI2. asierr.h containing definitions of code values returned in asi_err()

ASI Functions

The ASI library contains functions that access the database by converting SQL expression to standarddata structures that are transferred to the driver

ASI Functions

ASI Deals with three types of data

Page 108: 2_Programming in AutoLISP

���

Internal Data

ASI_SINT Internal integer

ASI_SREAL Internal real

ASI_SCHAR Internal array

ASI_SNULL Null value

Host variables

ASI_HINT int

ASI_HREAL double

ASI_HCHAR null terminated character string

ASI_HSHORT short

ASI_HLONG long

ASI_HFLONT float

SQL data types

ASI_CHAR CHARACTER

ASI_NUMERIC NUMERIC

ASI_DECIMAL DECIMAL

ASI_INTEGER INTEGER

ASI_SMALLINT SMALLINT

ASI_FLOAT FLOAT

ASI_REAL REAL

ASI_DOUBLE DOUBLE PRECISION

Page 109: 2_Programming in AutoLISP

���

Database Processing

Interaction with any database is divided into seven steps

1. Connecting to database2. Opening a communication handle3. Compiling the original SQL statement4. Executing the SQL statement5. Fetching. This step follows the query execution6. Closing a communication handle7. Disconnecting from database

HANDLES

All ASI function passes information to each other by using handle. A handle is an ASI defined datastructure used for passing data back and forth between the application and the driver. There are threetypes of handle

1. Driver HandleUse of Driver handle is points to the active DBMS

2. Database HandleUse of Database handle is points to the active database

3. Communication HandleUse 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 abrief description

Driver-based FunctionsASI_CFGDRV Configures a driver

ASI_INITDRV Initializes a driver

ASI_INITSQL Sets up the environment

ASI_TERMALLDRV Terminates all drivers

ASI_TERMDRV Terminates a driver

Page 110: 2_Programming in AutoLISP

���

ASI_TERMSQL Terminates the ASI interface

Processing Functions

ASI_BND Defines input buffers

ASI_CDS Gets description of a column

ASI_CEX Compiles and executes in one step

ASI_CHDL Closes a handle to a database

ASI_COLSDSC Gets full description of all columns in a query

ASI_COM Compiles a SQL statement

ASI_CMT Commits a transaction

ASI_CURROW Gets the current row number

ASI_CVL Gets a column value from current row

ASI_DEL Deletes the current row while fetching

ASI_DUPL_COLSDSCDuplicates the column descriptor list

ASI_EXE Executes a SQL statement

ASI_FBK Fetches in backward direction

ASI_FBR Fetches the bottom row

ASI_FET Fetches in the forward direction

ASI_FTR Fetches the top row

ASI_GETTABLE Get the results of query as a linked listASI_LON Logs on to a database

ASI_LOF Log off from a database

ASI_OHDL Opens a handle to a database

ASI_OPR Gets the stage of SQL statement processing

ASI_RBK Rolls back a transaction

ASI_RLS_COL_DSC Releases memory allocated by as_dupl_colsdsc

ASI_RLSTABLE Rrlrases memory allocated by asi_gettable

Page 111: 2_Programming in AutoLISP

���

ASI_ROWQTY Gets number of rows in the selection set

ASI_SOB Sets output buffers

ASI_STM Gets the type of SQL statement

ASI_UPD Updates current row while fetching

Error Code Handling

ASI_ERR Gets an error code value

ASI_ERRMSG Gets an error message

ASI_SYNERRPOS Gets an SQL statement syntax error position

ASI_XERR Gets an error code value from the driver

SQL Statement Syntax

ASI and ASELQED support SQL syntax compatible with the ANSI X3.135-1989 SQL Standard. ASI isalso fully compatible with the ISO SQL Standard. A summary of SQL syntax and ASE SQL standardsfollows. The SQL standard listed is not a complete listed is of the ANSI standard. Some commands are asuperset of the ANSI standard.

SYNTACTIC NOTATION

1. Elements enclosed in square brackets ([ ]) are optional2. Elements with ellipses (...) following may be repeated one or more times3. Elements enclosed in braces ({ } ) are listed in sequence

ADS-Defined AutoLISP functions

These functions are defined by the ADS program acadapp and only available if that program is loaded.Before calling these functions, use the xload function to verify that acadapp is available.

1. (acad_colordlg colornum [flag])

Display the standard AutoCAD color selection dialogue box

The colornum argument is an integer in range 0-256

The acad_colordlg function returns the color number that the user selects via the OK button. If the usercancels the dialogue box, acad_colordlg returns nil.

2. (acad_helpdlg helpfile topic)

Page 112: 2_Programming in AutoLISP

���

Display the standard AutoCAD Help dialogues box using a specified file. You can call this function fromyour AutoLISP routine to provide help on a standard AutoCAD command or own application specifichelp.

3. (acad_strlsort list)

Sort a list of strings by alphabetical order. The list argument is the list of string to be sorted. Theacad_strlsort function returns a list of the same string in alphabetical order.

AutoLISP Access to ADS-defined Commands

These functions let you access ADS-defined AutoCAD commands from AutoLISP. They are availableonly 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 resultsto contain the message string; otherwise, the result is nil.The bherrs function is defined in acaddapp.exp.

(c:bhatch pt [ss] [vector])

calls the BHATCH command and performs a boundary hatch on the specified area. The c: bhatchfunction is defined in acadapp.exp.

(c; ppoly pt [ss] [vector])

Calls the BPOLY command and creates a boundary Polyline. The c: bpoly function is defined inacadapp.exp

(c: psdrag mode)

Calls the PSDRAG command and sets the integer value mode. The mode argument is an integer thatequals either 0 or 1. The c: psdrag function is defined in acadapp.exp.

(c: psfill ent pattern arg1 [arg2] ... )

Fill a polyline with a postscript file. The ent argument is the name of polyline. The pattern argument is astring containing the name of the fill pattern. The pattren string must be identical to the name of fillpattern 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 apoint specifying the insertion point of the PostScript block.

Page 113: 2_Programming in AutoLISP

���

(mirror3d ss str pt xy )

Uses the MIRROR3D command to mirror 3D object about an arbitrary 3D plane.

(rotate3d ss str pt xy)

Uses the ROTATE3D command to rotate 3D object an arbitrary 3D axis

(solxxx arg1 arg2 . . . )

Calls most REGION MODELER COMMANDS. Solxxx is name of a command; arg1 and arg2 areordinary AutoLISP expressions. The REGION MODELER supports the following commands inAutoLISP.

Command Returned value

SOLAREA A real number

SOLFEAT A selection set

SOLIDIFY A selection set

SOLINT A selection set

SOLMASSP A list of mass properties

SOLMESH The number 1

SOLPURGE The number 1

SOLSEP The number 1

SOLSUB A selection set

SOLUNION A selection set

SOLVAR The value of the system variable

SOLWIRE The number 1

Page 114: 2_Programming in AutoLISP

���

ADS LIBRARY EXTENSIONSExternally Defined AutoCAD Functions

These functions are standard AutoCAD facilities externally defined by the ADS program acadapp. Theyare available only if acadapp is loaded, which it is by default. You can invoke them via ads_invoke (), asdescribed here.

1. (acad_colordlg colornum [flag])

Display the standard AutoCAD color selection dialogue box

The colornum argument is an integer in range 0-256

The acad_colordlg function returns the color number that the user selects via the OK button. If the usercancels the dialogue box, acad_colordlg returns nil.

2. (acad_helpdlg helpfile topic)

Display the standard AutoCAD Help dialogues box using a specified file. You can call this function fromyour AutoLISP routine to provide help on a standard AutoCAD command or own application specifichelp.

3. (acad_strlsort list)

Sort a list of strings by alphabetical order. The list argument is the list of string to be sorted. Theacad_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 codesamples. An error () call has this format:

Error (n, “error message”)

This function sets the global integer variable cal_err to the value of n, and display an error message. Ifcal_err is already nonzero , the error () call has no effect. This avoids printing several error messagescaused by single error.

The “ERROR MESSAGE” string is used three ways, depending on the value of n:

1. If n is zero, error () prints the message string.

2. If n is the number of an error used by the standard calculator functions, error () prints the standarderror message, with the string inserted into the variable portion of the standard message, if any.

Page 115: 2_Programming in AutoLISP

���

3. If n is less than zero, error() prints the negative number and ignores the message string. This is usefulfor debugging and for reporting internal errors

The SAGET Library

The SAGET library enhances the functionality of the standard ADS library. It provides a set of inputfunctions equivalent to the standard ADS input functions ads_getxxx() plus some related utilityfunctions.

The extended user-input functions take exactly the same parameters and work exactly the same as theirADS counterparts. However , they provide addional functionality, as follows:

1. Keyboard/AutoLISP input redirection

2. Geometry calculator support

3. Construction plane support

If you want to use the SAGET library in your ADS application, you must include the header file saget.c inyour source files and compile your ADS application along with the source files saget.c and util.c. you canlook at these source files to see how this library is implemented.

NOTE: ALL FIG. S COURTESY FROM AUTODESK MANUAL

Page 116: 2_Programming in AutoLISP

���

Page 117: 2_Programming in AutoLISP

���