14 Lessons For New AutoLISP Pro

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 85

14 Lessons For New AutoLISP Programmers

(defun c:wtext (/ fd md tx)


(initget "Add Replace")
(setq md (getkword "\nAdd/Replace: "))
(cond

((= md "Add")
(setq fd (open "c:/lines.txt" "a"))
)
(T
(setq fd (open "c:/lines.txt" "w"))
)
)
(while (/= (setq tx (getstring "\ntx: ")) "")
(write-line tx f)
)
(close fd)
(princ)
)
(c:wtext)

By Jos van Doorn - 2013

Legal Notice:

This e-book is copyright protected. This is only for personal use. You cannot
amend, distribute, sell, use, quote or paraphrase any part or the content within this
e-book without the consent of the author. Legal action will be pursued if this is
breached.

Disclaimer Notice:

Please note the information contained within this document is for educational
purposes only.

Every attempt has been made to provide accurate, up to date and reliable complete
information no warranties of any kind are expressed or implied.

Readers acknowledge that the author is not engaging in rendering legal, financial
or professional advice.

By reading any document, the reader agrees that under no circumstances are we
responsible for any losses, direct or indirect, which are incurred as a result of use of
the information contained within this document, including – but not limited to
errors, omissions, or inaccuracies.

About Me:

Hello, I’m Jos van Doorn. I live in Malaysia. But I'm not a Malaysian. I'm
originally from Holland. I moved to Malaysia about 25 years ago.

That was in Holland. I started with AutoCAD. I was interested in programming for
AutoCAD, so I learned about AutoLISP.

By now I'm very good at programming in AutoLISP. I have written books about
AutoLISP and I have written marshy AutoLISP programs.

The AutoLISP programs were written for engineering firms and architects. They
helped them to save a lot of time with AutoCAD.

That is the problem with AutoCAD. It takes a lot of time before an AutoCAD
drawing is created. And once created it has to be checked.

It takes hours, and sometimes days, before an AutoCAD drawing has been created
and can be used. It takes a lot of time and money.

Not so if an AutoLISP program is used for creating AutoCAD drawings. With an


AutoLISP program an AutoCAD drawing is created within one minute.

And that is important. The AutoCAD drawing can be used right away. Check the
AutoCAD drawing is not needed. It is made according standards.

I started my own business in 2012. The business is called “Make AutoCAD Fast”.
I'm writing a blog and a newsletter.

Contents

1. Contents 4
2. Starting With AutoLISP 5
3. Introduction 6
4. Basic Concepts 8
5. Arithmetic And Geometric Functions 17
6. Parametric Drawing 27
7. Predicates, Test, And Repeat Functions 44
8. Presentation Of Routines 54
9. List Functions 69
10. External Files 83
11. AutoLISP And AutoCAD Database 93
12. System Management 116
13. System Variables 123
14. Dimension System Variables 137
15. DXF Table 138

Starting With AutoLISP

You are working with AutoCAD. You know how it is. It takes a lot of time to create
a drawing. And when the drawing is finished, you must check it.

You can speed up AutoCAD with he help of AutoLISP. You can write an AutoLISP
program, that creates a complete AutoCAD drawing for you.

An AutoLISP program can create an AutoCAD drawing in seconds. You no longer


need hours for creating an AutoCAD drawing.

And that is a very important advantage of having an AutoLISP program for


creating your AutoCAD drawings. You don't need to check it.

The AutoLISP program creates an AutoCAD drawing in accordance with the


specifications that are laid down in the program.

Something you should know about. AutoLISP is not a very complicated


programming language. You can easily learn AutoLISP and write your own
programs.

This is an AutoLISP course. In the e-book is explained how AutoLISP works. See
how easy it is.

Introduction

AutoCAD and IntelliCAD have many useful base commands. That is why these
programs can be used by many disciplines.

But as a user of AutoCAD or IntelliCAD you could be looking for specific


commands. You may want to use commands that are not basic.

Suppose you are an architect. You are working with AutoCAD or IntelliCAD. You
would like a command that can be used for drawing walls.
Or you have an engineering firm. You too are working with AutoCAD or
IntelliCAD. You would like to have a command that can be used for drawing shafts.

Create Commands

You will not find those commands in AutoCAD or IntelliCAD. But you can create
those commands using AutoLISP.

With AutoLISP you can create screen menus, pulldown menus, dialog boxes, and
buttons for starting a specific command.

In this course is explained what can be done with AutoLISP. After reading and
studying the course, the reader is able to create own commands.

What Is Needed:

- The full version of AutoCAD. AutoLISP is only supported by the full version of
AutoCAD.
You can also take any version of IntelliCAD. All versions of IntelliCAD support
AutoLISP.

- A text editor. You can work with Notepad from Windows. But you can also
download Textpad from this web site:

http://www.textpad.com/
Textpad is not free. The price is about $ 26 for a single user.

If you do not buy it, you can still work with it. But every now and then a dialog box
shows up asking if you want to continue evaluating the program.

- Your need to have a RAM memory of your computer of minimal 640 KB. And you
need to have a hard disk in your computer.

Most computers have that.

Basic Concepts

With AutoLISP you can write programs that perform tasks or that make
calculations. AutoLISP makes the AutoCAD program powerful.

AutoLISP is a dialect of the programming language LISP. LISP was developed by


John McCarthy. It is the second higher programming language after FORTRAN.
The name LISP is made up by the word LISt Programing or LISt Processing.
There is also said that it comes from "Lots of Insane Stupid Parenthesis".

Any AutoLISP program contains a lot of brackets that seem to be useless. But if
you have a closer look at AutoLISP, then you will see how logical it is.

AutoCAD started with AutoLISP. They used the LISP programming language for
the following three reasons:

- Flexibility
- Simplicity
- Interpretability

LISP is very flexible. In many ways functions and variables can be defined.
Variables can contain many types of values.

Learning LISP is simple. It is not complicated. And it is simple to work with


AutoLISP programs and to create them.
AutoLISP is not compiled. The advantage is that AutoLISP can be used right away
and mistakes can easily be corrected.

For starters we are now going to talk about using AutoLISP at the command
prompt of AutoCAD or IntelliCAD. Later we write programs.

Here is a first example. We want to insert a block into the drawing. But the block
should be inserted with the scale 17 divided by 7.

You can use a calculator and find the exact number of the scale. But there is
another way. You can use AutoLISP. This is how:

Command: Block
Blockname: DEMO
Insertion point: pick a point in the drawing area X scale factor: (/ 17 7)
Y scale factor: same
Rotation angle: 0

Do you see? As there was asked for the scale factor, (/ 17 7) was entered. AutoLISP
calculates how much that is and the result is used.

Maybe you want to see how much that is. Enter the following line at the command
prompt and the answer will come out:

(/ 17.0 7) 2.42857
That is important. We want to see a real number as the result. So we cannot enter (/
17 7). If we do than an integer is the result. And that is 2.

Let's now talk about the basic concepts of AutoLISP. In AutoLISP we talk about
atoms, lists, functions, handling data, and some lexical agreements.

Atoms

An atom is a number of characters or a number. ABC,


-12, -20, and 12.345 are examples of atoms. An atom with no value is nil.

In AutoLISP you find the follwing types of atoms:

- Symbols
- Strings
- Real numbers
- Integers
- Built-in functions
- File descriptors
- Entity names
- Selection sets

Data is stored in a symbol. PT could be the symbol for a point. ET could be the
symbol for an entity. NR could be the symbol for a number.

A string is surrounded by quotation marks. Here are two examples of strings:


"This is a text"
"First point: "
Real numbers are number with a decimal part. Here is a real number:
12.345
An integer is a number without a decimal part. The number is rounded. 12 is an
integer.
Built-in functions act on one or more atoms. Here are two built-in functions:
+ - addition / - division

When AutoLISP works with external files, then each file gets a file descriptor. The
name of the file descriptor could be:

<file #E872>

Every part that has been drawn in AutoCAD or IntelliCAD is an entity. The name
of the entity could be:
<Entity name: 612345614>
A selection set is a couple of entities that have been selected in AutoLISP. This is
how it may look: <Selection set: 23>

Lists

A list is a couple of elements grouped between brackets. The elements could be


atoms or other lists. Here are two examples:

(1 2 3 4 5)
(1 (2 3) 4)

A point in AutoCAD or IntelliCAD is a list of two or three values. In the list are the
X value, the Y value, and maybe the Z value.

For a 2D point the list of the point consists of two values. It could look like (100
200).
For a 3D point the list has got three values. The list could look like (50 125 76).
A list can contain no elements. In that case it is represented as (). The value of the
list is nil.

Functions

Here is an example of a function.


(/ 32.0 7)
As you can see. The function is in a list. These are the atoms of the list:

/ - function
32.0 - real number
7 - integer

In this tutorial all AutoLISP functions will be explained. There is said what
argument are needed by the function.

This is how it may look:


(moo <text> <number> ...)

In the example the name of the function is MOO. The first argument of the function
is a text. And the second argument is a number.

The three dots indicate that more numbers can be added to the list. So you can have
the following:
(moo "This is a text" 12)
(moo "Here is another text" 34 1 67 8.0)

When an argument can be added to the list, but the argument is not really needed,
the square brackets are used. See how:

(foo <text> [<number>])


So the list could look like this:
(foo "A new house") (foo "City" 12)

Handling Data

AutoLISP can store values in symbols that are defined by the program. For doing
that the SETQ function is used.

This is the syntax of the SETQ function:


(setq <symbol1> <expresssion1> [<symbol2> <expression2>] ...)

With this function the result of expression1 is bound to symbol1. More symbols and
expressions can be added to the list.
So you can have:

(setq nr 4)

(setq n1 12 n2 45 n3 4.5

That is important. Never use the name of a function as the name of a symbol. So
don't have symbols with the name SET.

You can check the value of a symbol. Suppose we enter the following at the
command prompt of AutoCAD or IntelliCAD:

(setq radius 234)

To check the value of the symbol RADIUS we enter the following at the command
prompt of AutoCAD or IntelliCAD.

!radius
The value of that symbol is given back by AutoCAD. In our case 234 is given back.

To find the value of a symbol you can also use the EVAL function. So you could
write at the command prompt of AutoCAD or InteliCAD:

(eval radius)

There is another function that can be used. But that function doesn't give back a
value. The function is the QUOTE function.
(quote radius) would give back RADIUS

Lexical Agreements

Here are the most important lexical agreements for AutoLISP:

- When programming lower case characters can be used as well as upper case
characters. Unless something is said in the syntax of the function.

- Symbol names can consist of all characters, except the following characters:
().'";
- The following characters are used as end character:
( ) ' " ; (space) (end of line)
- Expressions such as formulas can be put on several lines
- More than one space between names are seen by AutoLISP as one space.
- Symbol names and function names cannot start with a number.
- Integers can start with + or -. The range of integers is from -32768 till + 32767.

- Real numbers start with a number, a dot, and then more numbers. -4 is not a real
number. 0.4 is.

- Texts are surrounded by quotation marks. The back slash is used as control code.
The following control codes are available:

\\ - \
\e - escape character
\n - new line
\r - return
\t - tab
\nnn - octal value of the character

- The single quotation mark (') is used as an abbreviation for the QUOTE function

- You can add comments to the AutoLISP program. To do that place a semi colon
in front of the comment. The comments is ignored by AutoLISP.
- The names of variables have a length of two. The names of a program or function
have a length of five. That is done to save memory.

Exercises

- Write an AutoLISP program that draws a rectangle. We use the LINE command
for doing that and you now about specifying a point.

- Calculate 15 divided by 3 using AutoLISP. Store the value in the symbol NR.

Arithmetic And Geometric Functions


Arithmetic Functions

That is important. In an arithmetic function the mathematical symbol always


comes before the function name. And then we have the numbers.

(+ <number> <number> ...)


The plus sign is a mathematical symbol.
Examples:

(+ 1 2) gives 3
(+ 12 13) gives 25
(+ 1 2 3 4 5) gives 15

(- <number> <number> ...)


Examples:

(- 50 40) gives 10
(- 40 30 5 0) gives 5
(- 10 20) gives -10

(* <number> <number> ...)


Examples:

(* 2 3) gives 6
(* 12 15 2) gives 360
(* 3 -4.5) gives -13.5

(/ <number> <number> ...)

(/ 100 2) gives 50 (/ 100 2.0) gives 50.0 (/ 100 20 2) gives 5


(1+ <number>)
Example:
(1+ 5) gives 6
(1- <number>)
Example:
(1- 10) gives 9
(abs <number>)

This function gives the absolute value of the number. The number can be a real
number of an integer.

Examples:
(abs 100) gives 100 (abs -97.25) gives 97.25
(max <number> <number> ...)

This function gives back the number that is the maximum of all the numbers. The
number can be a real number or an integer.

Examples:
(max 12 20) gives 20 (max 5,5 7) gives 7
(min <number> <number> ...)

This function is the opposite of the previous function. Now the minimum number is
given back. The number can be a real number or an integer.

Examples:
(min 4.07 -144) gives -144 (min 88.5 19 5) gives 5
(gcd <number> <number>)

Now we are going to do a complicated calculation. With this function the greatest
common divisor is found. The numbers are integers.

(gcd 81 57) gives 3 (gcd 12 20) gives 4


(rem <number> <number> ...)

This function calculates how much remains after a division. The numbers can be
integers and real numbers.

Examples:
(rem 42 12) gives 6 (rem 9 4) gives 1
(exp <number>)

This function raises e to the mach of the number. The number can be an integer as
a real number. The result is always positive.
Examples

(exp 1) gives 2.71828


(exp 2.2) gives 9.02501
(exp -0.4) gives 0.67032

(expt <base> <exponent>)

Now the base number is raised to the mach of the exponent number. The base and
the exponent can be integers and real numbers.

Examples:
(expt 2 4) gives 16 (expt 3.0 2) gives 9.0
(sqrt <number>)

This function calculates the square root of the number. The number can be an
integer as well as a real number.

Examples:
(sqrt 9) gives 3 (sqrt 2.0) gives 1.41321
(log <number>)

This function gives as result the natural logarithm of the number. The number can
be an integer as well as a real number.

(log 4.5) gives 1.50408 (log 1.22) gives 0.198851


pi
This is no function but a constant number. The value of the number is 3.1415926.
(cos <angle>)
This function calculates the co sinus of the angle. The angle is expressed in radians.
Examples:
(cos 0) gives 1 (cos pi gives -1
(sin <angle>)

The same as before. Except this time the sinus of an angle is calculated. The angle is
expressed in radians.

Examples:
(sin 1.0) gives 0.841471 (sin 0,0) gives 0.0
(atan <number> [<number>])

If the second number is not present, then the function gives back the tangent of the
first number in radians. The number of the angle can be between pi and -pi,

Examples:

(atan 0.5) gives 0.463648 (atan 1.0) gives 0.785398 (atan -1.0) gives -0.785398

If the second number is present, then the function gives back the inverse tangent of
the quotient of the two numbers.

Examples:

(atan 2.0 3.0) gives 0.588003


(atan -2.0 3.0) gives -0.68003
(atan -2.0 -3.0) gives -2.55359
(atan 1.0 0.0) gives 1.570796
(atan -0.5 0.0) gives -1.570796

Geometric Functions

(angle <point1> <point2>)

The function calculates the angle of the straight line going from poiint1 to point2. It
calculates the angle between the line and the active UCS.

UCS stands for User Coordinate System. And the angles are measured counter
clockwise. And the angle is given in radians.

Examples:
(angle '(1.0 1.0) '(1.0 4.0)) gives 1.5708 (angle ;(5.0 1.33) '(2.4 1.33)) gives 3.14159
(distance <point1> <point2>)

The function gives the distance between the two points. The distance is given in
screen units. If the value of the FLATLAND system variable is unequal to zero,
then 2D points are expected. If a 3D point is used, then the Z value is ignored.

Examples:
(distance '(1.0 2.5 3.0) '(7.7 2.5 3.0)) gives 6.7 (distance '(1.0 5.0) '(1.0 15.0)) gives
10.0
(inters <point1> <point2> <point3> <point4> [<on>])

The function calculates where the lines between point 1 and point 2 and point 3 and
point 4 cross. A point is given back.
When the optional argument ON is present and nil. then the two points are
considered to be infinite.
Examples:

(setq p1 (list 1.0 1.0) p2 (list 9.0 9.0) p3 (list 4.0 1.0) p4 (list 4.0 2.0)

(inters p1 p2 p3 p4) gives nil (inters p1 p2 p3 p4 T) gives nil (inters p1 p2 p3 p4 nil)


gives (4.0 4.0)

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

This function gives as a result a point that is under an angle from the point that has
been given and on a distance.

The angle is expressed in radians, as always is done in AutoLISP.

If the FLAYLAND system variable is se tot nil, then the resulting point can be a 3D
point. Otherwise it is only a 2D point.

Example:
(polar '(1.0 1.0) 0 4.0) gives (5.0 1.0)
(osnap <point> <mode>)
Depending on the value of the text of the mode a point is calculated. These are the
modes there are:

Nearest snap - "nea" Endpoint snap - "endp" Midpoint snap - "midp" Center snap
- "centre" Perpendicular snap - "perp" Tangent snap - "tan" Quadrant snap -
"quad" Insertion point snap - "int" Point Snap - "pnt" Intersection snap - "int"

Example: (setq pt (osnap pt "nea"))

Exercises:

1. What is the result?


(+ 5 (- 10 2) 7)
2. What is the result? (* 8 (setq t "text" a 3))
3. What is the result?
(max -11 100 -144)
4. What is the result?
(rem 34 12)
5. The angles in AutoLISP. Are they calculated in degrees or radians?

6. When the FLATLAND system variable has got a value unequal to zero, is then a
2D distance calculated or a 3D distance with the DISTANCE function?

7. Calculate where two lines cross. The lines are infinite.


8. In the POLAR function. Is the angle given in radians or in degrees?
9. What is the result?
(polar '(100 100) pi 50.0))
10. Calculates the ANGLE function an angle between two lines?

Parametric Drawing

We have learned about Arithmetic And Geometric Functions. We saw how they are
used. But we haven't seen a program yet.

An AutoLISP Program

Guess what. Here I have the listing of an AutoLISP program for you. Here I have
the listing of the NEWDR.LSP program for you.

(defun c:newdr (/ p1 p2 p3 p4 p5 p6 p7 sd ts ws) (setvar "cmdecho" 0)


(setq p1 (getpoint "\nPosition door: ")

sd (getdist "\nStructural dimension: ") ws (getdist "\nWidth style: ") ts (getdist


"\nThickness style: ") p2 (polar p1 0 ts)
p3 (polar p2 (/ pi 2) ws)
p4 (polar p3 pi ts)
p5 (polar p2 0 sd)
p6 (polar p3 0 sd)
p7 (polar p3 (/ pi 2) sd)

)
(command "pline" p1 "w" 0 0 p2 p3 p4 "c") (command "copy" "l" "" p1 p5 "")
(command "pline" p2 p5 "")
(command "copy" "l" "" p2 p3 "")
(command "pline" p3 p7 "")
(command "arc" p6 "c" p3 p7)
(command "zoom" "a")
(command "zoom" "0.8x")
(setvar "cmdecho" 1)
(princ)
)

(c:newdr)

Using the program a door will be drawn. See how the door looks. As you can see.
The door has different sizes and a position.

That is so good about the listing of an AutoLISP program. You can save it on your
hard disk and use it again. You can copy it to a text program.

You can type its listing in Notepad of Windows. I prefer to type it in TextPad. You
know how you can get TextPad.

That is important. When the listing of an AutoLISP program is saved, it is saved


under the name NEWDR.LSP. Next load it into your CAD program.

Load An AutoLISP Program Into Your CAD Program

Let's talk about how to load an AutoLISP program into your CAD program. That
must be done first before you can use the AutoLISP program.

I will talk about loading the AutoLISP program into IntelliCAD. Loading it into
AutoCAD is done in the same way. So don't worry.

You are in IntelliCAD. Click on Tools in the menu. In the pop-up menu click on
Load Application. The Load Application files dialog box is displayed.

In the dialog box click on the Add File button. You can go to different folders and
you can select the AutoLISP file that you want to load.

Click on the file. And click on the Open button. You come back into the Load
Application file dialog box. Click in the Load button.

The AutoLISP file is now loaded into your CAD Program. In this case it is loaded
into IntelliCAD. And you can start it by typing its name at the prompt.

Added To The AutoLISP program

Before I talk about the AutoLISP program, I want to say something about what has
been added to the program. At the end you see:

(c:newdr) Through that line the AutoLISP starts after it has been loaded into
IntelliCAD. As you can see. The name of the AutoLISP program is in the line.

Functions In The AutoLISP Program

In the AutoLISP program we find functions The first function we find it the
DEFUN function. Here is the syntax of the DEFUN function:

(defun <symbol> <argument list> <expression> ...)

Th DEFUN function is used for defining an AutoLISP program. SYMBOL is the


name of the new AutoLISP program.

In the argument list you find all the arguments that the new AutoLISP function
needs to run properly. If not all arguments are there, then an error occurs.

In the argument list you can find a slash. After the slash comes a list of variables.
Those variables are local variables.

The local variables only have a value in the function Out side the function they have
no value. Or the value of them is nil.

If no argument list is given then the symbol of an empty list must be used. This is
how that symbol looks like: ().

Variables that are not defined as local have a value outside the function They have
a value when the function is no longer running. Here are some examples:
(defun funct (x y) - the function has two arguments
(defun funct (/ a b) - the function has two local variables
(defun funct (z / a) - the function has no argument and one local variable

(defun funct () - the function has no arguments

After the argument list follow expressions that must be evaluated as the function is
running. Here is how a function can be used at the command prompt:

Command: (defun plus10 (nr) >1 (+ 10 nr)


>1 )
PLUS10

Command: (plus10 5) 15
Command: (plus 10 -3) 7

The DEFUN function can also be used to create a new AutoLISP command If that
is done then in front of symbol there is C:.
You can only define a new AutoCAD command with an empty argument list. But
you can define local variables See the program. There it is done.

In the NEWDR.LSP program several functions are used that are new. The
functions have a name that starts with GET and are used for getting information.

Getting Information

There are many AutoLISP functions that can be used for getting information. Here
is a list of all those functions.

(getpoint [<point>] [<prompt>])

With this function the AutoLISP program pauses and the user can enter a point or
pick a point. Entering a point in the function is optional.

If a point is added to the function then a rubber band is drawn from that point and
the user can pick a point. It can be used to let the user pick two points.

The prompt is displayed at the command prompt of AutoCAD or IntelliCAD as


there is asked for a point. To let the user know what is expected.

Example:

(setq p1 (getpoint “\nFirst point: “) p2 (getpoint p1 “\nSecond point: “)


)
(getcorner <point> [<prompt>])

In this function a point is needed. A rectangle is drawn starting in that point. And
two points of a window are specified.

Example:

(setq p1 (getpoint “\nLower left point: “) p2 (getcorner p1 “\nUpper right point: “)


)

(getdist [<point>] [<prompt>])

This functions allows the user to enter a distance. The distance can be entered by
picking two points in the drawing area or by entering a number.

Optional is adding a point to the function. If that is done, then a rubber band is
drawn from that point and the distance is measured from that point to the new
point.

Example:

(setq p1 (getpoint “\nStartpoint: “) p2 (getdist p1 “\nDistance: “)


)

((getint [<prompt>])

Now the user can enter an integer. A prompt can be added to the function If it is
added, then the prompt is displayed at the command prompt.

Example:
(setq in (getint “\nInteger: “))
(getreal [<prompt>])

This function is the same as the previous function. Except now the user can enter a
real number. So the user is more flexible.

Example:
(setq re (getreal “\n Real number: “)
(getangle [<point>] [<prompt>])

Now the user can enter an angle. A point can be added to the function. But that is
optional. Suppose no point is added to the function
Then a first point is picked by the user. The cursor is moved. A rubber band is
drawn from the first point. And a prompt is displayed.

The prompt says “Second point”. The second point is picked and the angle between
the two points is calculated But the angle in radians.

If a point has been added to the function, then there is not asked for a second point.
A rubber band is drawn from the point in the function.

The angle between the point of the function and the point that is picked is
calculated. Again. The angle that is calculated is in radians.

Example:
(setq an (getangle “\nAngle: “))
An angle in radians is given back

(setq pt (getpoint “\nStart of angle: “) an (getangle pt “\nEndpoint of angle: “)


)

An angle in radians is given back


(getorient [<point>] [<prompt>])

This function works as the GETANGLE function. It can be used to measure angles
that have been entered. But there is something with the zero angle.

You know where the zero angle is. Standard that angle is in the east. And the angles
are measured counter clockwise.

Suppose the user has changed the zero angle and it is not pointing to the north.
With the ANGLE function angles are measured from the new zero angle.

But with the GETORIENT function the change of the zero angle is not considered.
There is always measured with a zero angle in the east

(getstring [<cr>] [<prompt>])

Now the user can enter a string. But take care. The CR argument can be added to
the function and it is supposed not to be nil.

If the CR argument is not entered, then every space in the text is seen as ending the
function. So what comes after the space is not regarded.
Another consideration. With the GETSTRING function only texts with a length of
132 characters can be read. If longer, than only the first 132 characters count.
Example:
(setq tx (getstring “First name: “)) (setq tx (getstring “Full name: “)
(getkword [<prompt>])

The GETKWORD function is always used in combination with the INITGET


function. With the INITGET function is defined what entries are valid.

When the user enters something that is not defined in the INITGET function, then
the GETKWORD function is repeated.

Example:
(initget “Yes No”)
(setq aw (getkword “\nWhat is your answer? (Y/N)”))
(initget [<bits>] [<text>])

The INITGET function can be used in combination with all the functions that start
with GET, except the GETSTRING function and the GETVAR function

This is the meaning of the bits in the INITGET functions


Bit Meaning

1 empty input not allowed.


2 null value not allowed.
4 negative values not allowed.
8 limits are not checked, even if LIMCHECK is engaged.
16 3D points are preferred instead of 2D points. 32 An dash line is used when a
rubber band or box is drawn.

The bits can be combined. The value of the bits can be as much as 63.
Example:
(initget (+ 1 2 4))
(setq th (getdist “\nThickness: “))

Here is an overview of how the GET functions can work with the INITGET
function And what entry can be specified using the INITGET function:

Function No No No No 3D Use null zero nega- li- points dashes tive mits

GETINIT X X X
GETREAL X X X
GETDIST X X X X X GETANGLE X X X GETORIENT X X X GETPOINT X X
X X GETCORNER X X X X GETKWORD X
GETSTRING
GETVAR

With the text argument you can specify what text are allowed as entry. We already
saw how that works This is how the text can look:
“Word1 Word2 WORD3,ABBREVIATION”

The individual words are separated by spaces. The words are written in lower case.
The characters in upper case are the abbreviations.

So to enter “word1” the user only has to enter a “w”. Through the text in INITGET
there is seen that the entry is “word1”.

If the user wants to enter “word2”, the he can enter the characters WO. Those
characters are the abbreviation of “word2”.

There is a second way if specifying what abbreviations are allowed. Specify the
complete word and the abbreviation with a comma between them.

Suppose we can enter “ltype”, but we can also enter “lt” as an abbreviation This is
how it is specified in the text of INITGET.

“LINETYPE,LT”
Example:
(initget 1 “New Status”)
(setq pt (getpoint “\nNew/Status/<first point>: “)

The user can pick a point or he can go for “New” or “Status”. Given in nothing is
not allowed. That is specified by the one bit.

Using IntelliCAD Commands

You can use IntelliCAD commands in your AutoLISP program. The same goes for
AutoCAD commands. They are used in the same way.

This is the syntax of how IntelliCAD command are used in an AutoLISP program:
(command <argument> ...)
Here is how an IntelliCAD command can be sued in an AuytoLISP program:

(setq p1 (getpoint "\nFirst point: ") p2 (getpoint p1 "\nSecond point: ")


)
(command)
(command "line" p1 p2)
(command "")

Two points are entered and assigned to the variables P1 and P2. Next there is a line
with COMMAND. The effect of that line is a break.

Then a line is drawn from point P1 to point P2. And in the last line the Line
command is terminated. An empty text is seen as a space.

The argument can be a text, a real or integer number. Using the COMMAND
function without argument is the same as Control C.

Important. The DTEXT command and the SKETCH command require input from
the keyboard and can therefore not be used in an AutoLISP program.

The same goes for the PLOT, PRPLOT, and the SCRIPT command.

You can add PAUSE in the COMMAND function. If you do, the command pauses
and the user can give an input. The command keeps on running.

Here is how it can be done:


(command "circle" (list 5 5) pause
"line" (list 5 5) (list 7 5)
)

In the example there is started with the CIRCLE command. The center point is set
at the point 5,5. And then there is a pause.

The user can move the cursor and set the radius of the circle. After that is done, a
line is drawn from point 5.5 to point 7,5.

That is important. To find out what arguments are needed to run a command in
AutoLISP. Go to IntelliCAD and start the command.

Take for instance the MOVE command. When the command starts this where is
asked for:

- Selection of entities to move:


- Vector/<Base point>:
- Displacement point:

After entities have been selected, then the selection is to be terminated. That is done
by clicking on the right mouse button. Or an empty string is given.
Next a base point is entered and then a
displacement point is entered. This is how the MOVE command can be used in an
AutoLISP program.

(command "move" ss "" p1 p2)

SS stands for a selection set. A selection set has been defined previously. The points
P1 and P2 have been picked before.

Another AutoLISP Program

Here is another AutoLISP program. The user is asked to pick two points in the
drawing area. And then he enters the height of the text and he enters a number.

A line is drawn. And the circle for the number is drawn. Next the number is drawn.
And a complete drawing is created.

Here is the complete program:


(defun c:nrinc ()
(setvar “cmdecho” 0)

(setq p1 (getpoint "\nFirst point: ") p2 (getpoint p1 "\nSecond point: ") th (getdist
"\nHeight of number") nr (getint "\nNumber: ")
an (angle p1 p2)

)
(command "line" (polar p1 an th) p2 "" "circle" p1 th
"text" "m" p1 th 0 nr
)
(setvar “cmdecho” 1)
(princ) )
(c:nrinc)

And this is how it looks after the AutoLISP program has run.
Exercise

We are going to create an AutoLISP program that is going to create the following
drawing. There is asked for:

- Start point
- End point
- Diameter pipe
- Diameter flange
- Thickness flange

This is how drawing looks. All where is asked for in specified in the drawing.
Predicates, Test, And Repeat Functions

Predicates are test functions. They can be used in combination with a repeat
function. With a repeat function operations are done again.

First let's talk about the predicates and then we will talk about the repeat functions.
There are many predicates and only a few repeat functions.

Predicates

(= <atom> <atom> ...)

This function checks if two or more atoms are the same. It can be used for numbers
and texts. If true the
result is T. Else it is nil.

Examples:

(= 4 4.0) T
(= 10 5.8) nil
(= "word" "word") T
(= 3 3.0 3.0) T
(/= <atom1> <atom2>)

This function is the same as the previous function. Except. Now there is checked
that two atoms are not the same.

Examples:
(/= 5 4) T
(/= "word" "word") nil
(< <atom> <atom>)

Now there is checked whether the fist atom is smaller


than the second atom. It works on numbers and it works on characters.

Examples:

(< 1 2 3) T (> 1 2 1) nil (< "a" "b") T (> "e" "b") nil

(<= <atom> <atom>)


The same as the previous function. Except this time the result is also T when the
atoms are equal.
Examples:
(<= 1 1) T (<= 1 1 2) nil
(> <atom> <atom> ...)

This time the function checks that the first atom is


greater than the second atom or the ones that follow.

Examples:
(> 5 3) T (> 5 3 1) T (> 5 3 7) nil
(>= <atom> <atom>)

As before. But now the result is T even if the atoms


are the same.

Examples:
(>= 4 4) T (>= "b" "a" "a") T
(equal <expression1> <expression2> [<fuxx>])

This function checks if two expressions are equal. You can enter a value for fuzz.
That value tells how much the two expressions can differ.

Example:
(equal 2 2) T (equal 2.3 2.5 0.1) T
(eq <expression1> <expression2>)
This function is the same as before. Except now you can not enter a value for fuzz.
Example:

(setq l1 '(a b c) l2 '(a b c) l3 l2

)
(eq f1 f3) nil (eq f1 f2) T
(atom <item>)
If item is a list, then the function gives back nil. In all other cases it gives back T.
(listp <item>)
This function checks if item is a list. If so it gives back T.
(boundp <item>)
This function checks if a value has been bound to the item.
Examples:
(setq a 5) (setq b nil)
(boundp a) T (boundp b) nil
(numberp <item>)
This function checks if an integer or a real number has been bound to the item.
(minusp <item>)
Now the function checks if the number bound to the item is negative.
(zerop <item>)
Now there is checked that the value bound to item is zero.
(and <expression> (expression> ...)
The function checks that all expressions have a value other then nil.
Example:

(setq a 10
b nil
c "Hello"

)
(and a b) nil (and a c) T
(or <expression> (expression> ...)
Now there is checked that at least one of the expression is unequal to nil.
Example:

(setq a 10
b nil
c "Hello"

)
(and a b) T (and a c) T
(not <item>)
The result of the function is T if the value of item is nil or nil as the value of the
expression is T.. (null <item>)
The result of the function is T is the value bound to item is nil.
(type <item>)
This function gives the type of the item. An item can have the following types:

REAL - real number


FILE - file descriptor
STR - string
INT - integer number
SYM - symbol
LIST - list
SUBSR - internal AutoLISP fucntion PICKSET - selection set
ENAME - entity name
PAGETB - function page table

Testfunctions

(if <test expression> <than expression> [<else expression>])


(progn <expression> ...)
(cond <test1> <result1> ...)
Example:
(defun c:blln3 (/ an aw p1 p2 th tx)

(setq p1 (getpoint "\nFirst point: ") p2 (getpoint p1 "\nSecond point: ") an (angle
p1 p2)
th (getdist "\nText height: ") tx (getstring "\nText: ")

)
(initget "Circle Three Four")
(setq aw (getkword "\nThree angles/Four angles/<Circle>: "))
(cond

((= aw "Three")
(command "polygon" 3
p1
(polar p1 an th)

)
)
((= aw "Four")

(command "polygon" 4
p1
(polar p1 an th)

)
)
(T

(command "circle" p1 th) )


)
(command "text" "m" p1 th 0 tx)

)
(c:blln3)

Repeat Functions

(while <test expression> <expression> ...)


Example:

(defun c:bline (/ an p1 p1 p2 rd) (setvar "cmdecho" 0)


(setq rd (getdist "\nRadius circle: ") p1 (getpoint "\nFirst point: ")

)
(command "circle" p1 rd)
(while p1

(setq p2 p1)
(setq p1 (getpoint p2 "\nNext point: ")) (if p1

(progn
(setq an (angle p2 p1))
(command "line" (polar p2 an rd)

(polar p1 (+ an pi) rd) ""


"circle"
p1
rd

)
)

)
)
(setvar "cmdecho" 1)
(princ)

)
(c:bline)

(repeat <number> <expression> ...)


Example:

(defun c:auton (/p1 rd an ds nr fn st fn p1) (setvar "cmdecho" 0)


(setq p1 (getpoint "\nPosition first circle: ")

rd (getdist p1 "\nRadius circle: ") an (getangle p1 "\nAngle between circles:

")
ds (getdist p1 "\nDistance circles: ") nr (getint "\nNumber of circles: ") fn (getint
"\nFirst number: ") st (getint "\nSize of steps: ")

)
(repeat nr
(command "circle" p1 rd)
(command "text" "m" p1 rd 0 fn) (setq fn (+ fn st)
p1 (polar p1 an ds)
)
)
(setvar "cmdecho" 1)
(princ)
)

(c:auton)

(foreach <name> <list> <expression> ...)


Example:
(foreach n (list 1 2 3) (* n 2))

This line gives out 6. That is the last calculation of the function. And this is how it
looks as the function is running:
Calculation Result

(* 1 2) 2
(* 2 2) 4
(* 3 2) 6

Exercise

Write an AutoLISP program Using the AutoLISP program a user can draw a line.
He can set the color of the line and he can set the linetype of the line.

This is the dialog of the AutoLISP program:

Command: NWLINE Color/Linetype/<first point>: C Color: 1


Color/Linetype/<first point>: L Linetype: hidden Color/Linetype/<first point>:
100,100 Close/Next point: 300,100 Close/Next point: 300,300 Close/Next point: C
Command:

Presentation Of Routines

We have four groups of functions that helps with the presentation of routines.

Let's say a calculation is performed by the program. Then the functions can be used
to show the result.

The four groups are:

1. Text screen functions


2. Graphical screen functions
3. Text functions
4. Conversion functions

Text screen functions

(graphscr)
This function switches the screen to the graphical screen. Only the drawing areas is
displayed.
(textscr)
Now the text screen is displayed. Now you can see what has been displayed at the
command prompt.
(getvar <name of system variable>)
In IntelliCAD you find system variables. Using this function you can find what
value is stored in the system variable.

(setvar <name of system variable> <value>)

We have two types of system variables. We have the read-only system variables and
we have the system variable that can get a new value.

Using this function the latter system variable can be given a new value. Here are
two examples of how the function is used:

(setvar :filletrad” 200) gives back 100 (setvar “cmdecho” 0) gives back 0

You can change the value of a system variable in an AutoLISP program. But it is
advisable to set it back to its original value at the end of the program.

Here is a program that shows how the value of the CMDECHO is changed in the
program.

(defun c:chvar ()
(setq cm (getvar "cmdecho"))
(setvar "cmdecho" 0)
(setq pt (getpoint "\nFirst circle: ")

rd (getdist "\nRadius circle: ") an (getangle "\nAngle between cicles: ") ds (getdist
"\nDistance circles: ") nr (getint "\nNumber of circles: ") fn (getint "\nFirst
number: ")
st (getint "\nSize steps: ")

)
(repeat nr
(command "circle" pt rd)
(command "text" "m"
pt
rd
0
fn
)
(setq fn (+ fn st)
pt (polar pt an ds)
)
)
(setvar "cmdecho" cm)
(princ )
)

(c:chvar)

(princ <expression> [<file description>])

This fiction sends the expression to the text screen.


And the result of the function is the expression. It can be any expression. Even if it
is no text.

Example:

(setq a 123 b 456


)

(princ 'a) gives A (princ a) gives 123


(princ b) gives 456
(princ “Hello”) gives “Hello”

If the expression is a text, then it can contain control codes. These are the control
codes that can be used.

\\ the back slash character \e escape


\n new line
\r return
\t tab
\nnn the character with the octal code nnn

The function PRINC can also be used without an expression. If that is done, then an
empty text is written to the text screen.

The function PRINC without an expression is always used at the end of an


AutoLISP program. You have seen examples of that.

You can give a file description in the PRINC function. If that is done, then the
expression is written to a file that is specified with the file description.

(prin1 <expression> [<file description>)


This function is the same as the PRINC function. Except control codes are not
evaluated.
(print <expression> [<file description>)
This function is the same as the PRINC function. Except before the expression a
new line is entered and after the function there is a space.

(prompt <text>)
This function prints a text to the text screen and gives back nil.
(terpri)

This function prints a new line to the text screen. It can only be used for printing to
the text screen. It cannot be used for printing to an external file.

Graphical screen functions

(grclear)

This function clears the graphical screen. Everything on the graphical screen is
made invisible. It is not removed from the screen.

What is on the graphical screen can be made visible again by using the REDRAW
command.
(grdraw <point1> <point2> <color> [<highlight>])
With this function a line is drawn from point 1 to point 2. It is drawn in the color
that is given.
If the number -1 is given for color, then the line is drawn in the inverse color.
Examples:
(grdraw (list 10 10) (list 50 5) 2)

Now a line is drawn from point 10,10 to point 50,50 in the color yellow. The number
of the color yellow is 2.

(grdraw (list 10 10) (list 50 5) -1)


Now a line is drawn that has the inverse color of where it is drawn on.

If the drawing area is black, then the line has the color white. If the color of the
drawing area is white, then the line is drawn in the color black. That is important.
A real line is not drawn. You cannot select the line with the ERASE command or
any other command.

If the REDRAW command is used, then the line disappears.

Text functions

(strcase <text> [<type>])


This function changes the text to lower case or upper case, depending on the type
argument. If it is there and not nil, then the text is written in lower case.

Examples:
(strcase “Text”) gives TEXT (strcase “TEXT” T) gives text
(strcat <text1> <text2> ...)
We have two or more texts and we want to combine them. Use this function for
doing that.
Examples:
(strcase “Auto” “LISP”) gives “AutoLISP” (strcase “six” “ “ “degres”) gives “six
degrees”
(strlen <text>)
This function gives back the length of a text. The length is given back as an integer.
Example:
(srlen “AutoLISP”) gives back 8
(substr <text> <start> [<length>])

This function gives back a part of the text. Depending on the number for start and
length. If no length is given, then the text starts at start.

Examples:

(substr “AutoLISP” 5) gives “LISP” (substr “AutoLISP” 5 2) gives “LI” (substr


“AutoLISP” 1 2) gives “Au”

Conversion functions

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

This function translates the angle in radians into a string. The way it is done
depends on the mode and the precision.

This is how it looks for the MODE argument:


Number Result

0 Degrees
1 Degrees/minutes/seconds
2 Degrees (400)
3 Radians
4 Land survey units

The PRECISION argument gives the number of digits behind the dot.
If the MODE and the PRECISION arguments is not used, then the values of he
AUNITS and the AUPREC system variables are used.

Example:

(setq p1 (list 500 133) p2 (list 240 133) an (angle p1 p2)

(angtos an 0 0) gives “180” (angtos an 0 4) gives “180,0000” (angtos an 1 4) gives


“180d0'0” (angtos an 3 4) gives “3.1416r” (angtos an 4 2) gives “W”

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

This function translates a real number to a string. The variables MODE and
PRECISION are used or the DIMZIN system variable is used.

These are the numbers that can be used for the MODE variable:
Number Result

1 Mathematical
2 Decimal
3 Feet and decimal inches
4 Feet and fractional inches
5 Fractures

Examples:

(rtos 17.5 1 4) gives “1.7500E+01” (rtos 17.5 2 2) gives “17.50” (rtos 17.5 3 2) gives
“1'-5.50”” (rtos 17.5 4 2) gives “1”- 5 1/2”” (rtos 17.5 5 3) gives “17 1/2”

(itoa <integer>)

This function works the same as the previous one. Except now integers are
translated into strings. And there are no arguments.

(atoi <text>)
This function translates a text into an integer.
Examples:

(atoi “97”) gives 97 (atoi “-3”) gives -3 (atoi “3.9”) gives 3

(atof <text>)
This function translates a text into a real number.
Examples:
(atof “97.1”) gives 97.1 (atof “-3”) gives -3.0
(fix <number>)
This function translates a number into an integer. The number can be an integer
and a real number.

Examples: (fix 3.7) gives 3


(fix 3) gives 3

(float <number>)
This fucntion translates a number to a real number. The number can be an integer
and a real number.
Examples:
(float 3) gives 3.0 (float 3.75) gives 3.75
(list <expression> ...)

This function turns one or more expressions intoa lsit. The expression can be a
number, a text, or a poiint.

Examples:

(list 'a 'b 'c) gives (A B C) (list 'a '(b c) “text”) gives (A (B C) “text”) (list 3.9 6.7)
gives (3.90000 6.70000)

(ascii <text>)
This function translates the first character of the text to the ASCII code of the
character.
Example:

(ascii “A”) gives 65 (ascii “a”) gives 97 (ascii “along”) gives 97

(chr <number>)
With this character of the ASCII code is given.
Examples:

(chr 65) gives “A” (chr 67) gives “B” (chr 97) gives “a”

(read <text>)
(This function gives as result the first atom or list of the text.
Examples:

(read “Auto”) gives Auto (read “(a)”) gives (a) (read “(a)(b)”) gives (a)
To finish, here is an AutoLISP program. The program is used to draw parking
spots. Here is how the parking spots look.

In the AutoLISP program you can specify the length of the parking spots. You can
also specify the width of each parking spot and the angle of the parking spots.

Here is the AutoLISP program. In the AutoLISP program conversion functions are
used and also functions. See for yourself.

(defun c:prkpl (/ an cm lg nr pt ra wd)


(graphscr)
(setq cm (getvar "cmdecho"))
(setvar "cmdecho" 0)
(screen)
(setq pt nil)
(while (/= (type pt) 'LIST)

(initget 1 "Width Length Angle")


(setq pt (getpoint

"\nWidth/Length/Angle/<Point>: ") )
(cond

((= pt "Width")
(setq wd (udist "Width" wd))
)
((= pt "Length")
(setq lg (udist "Length" lg))
)
((= pt "Angle")
(setq an (uangl "Angle" an))
)
)
)
(setq nr (uintg "Number of parking spots" nr)
an (* (/ an 180.0) pi)
)
(command "line" pt (polar pt 0 (* nr wd)) "") (repeat (1+ nr)
(command "line" (polar pt (+ an pi) lg) (polar pt an lg) ""
)
(setq pt (polar pt 0 wd))
)
(command "zoom" "all")
(command "zoom" "0.8x")
(setvar "cmdecho" cm)
(princ)
)

(defun screen () (if wd


wd
(setq wd 2400)

)
(if lg
lg
(setq lg 4800)
)
(if an
an
(setq an 90)
)
(if nr
nr
(setq nr 10)
)
)

(defun uintg (tx df / pt) (if df


(progn
(setq tx (strcat "\n" tx " <" (itoa df) ">: "

)
(initget)
)
(progn
(setq tx (strcat "\n" tx ": "))
(initget 1)
)
)
(setq pt (getint tx))
(if pt
pt
df
)
)

(defun uangl (tx df / pt)


(if df

(setq tx (strcat "\n "


tx
" <"
(itoa df) ">: "

)
)
(initget)

)
(progn
(setq tx (strcat "\n" tx ": ")) (initget 1)
)
)
(setq pt (getint tx))
(if pt
pt
(setq pt df)
)
)
(defun udist (tx df / pt)
(if df

(progn
(setq tx (strcat "\n "
tx
" <" (rtos df 2 2) ">: "

)
)
(initget)

)
(progn
(setq tx (strcat "\n" tx ": ")) (initget 1)
)
)
(setq pt (getdist tx))
(if pt
pt
(setq pt df)
)
)

(c:prkpl)

Exercise:

Earlier you have written an AutoLISP program that draws a pipe with two flanges.
Change the program. Ask as in the parking spot program.

The following questions are asked: “Diameter pipe/diameter flange/thickness


flange/<startpoint>:”
“End point:”

The diameter of the pipe, the diameter of the flange, and the thickness of the flange
can be entered. These are the prompts that show up:

“Diameter pipe:” “Diameter flange:” “Thickness flange:”

List Functions
If we talk about programming languages. Most programming languages work with
arrays. You can store information in arrays.

In AutoLISP we do not have arrays. We have lists in AutoLISP. And you can use a
list to store any kind of information in it.

There are a lot of functions that can be used for working with a list. Here they are:
(list <expression> ...)
This functions makes a list of a number of items.
Examples:
(list 'a 'b 'c 'd) gives back (list A B C D) (list 'a '(b c) "text") gives back (list A (B C)

"text")
(list 3.95 5) gives back (list 3.95 5) (list (100 100)) gives back ((100 100))

(append <list> <list>)


This function makes a new list out of two functions.
Examples:
(append '(a b) '(c d)) gives back (A B C D) (append '((a) (b)) '(c d)) gives back ((A)
(B) C D)
(cons <new first element> <list>)

With this function a new list is created. The new list has got the new first element as
its beginning. Here are examples:

(cons 'a '(b c d)) (cons '(a) '(b c d)) gives back (A B C D) gives back (((A) B C D)

The new first element can also be an atom such as a number. If that is so, then what
is given back is a so called dotted pair.

A dotted pair consists of two elements that are separated by a space, a dot, and a
space. You see dotted pairs in the AutoCAD database.

Examples:

(cons 2 'a) gives back (2 . A) (cons 6 "0") gives back (6 . "0") (cons 2.4 'a) gives back
(2.4000 . A)

(setq p1 (list 10 10)) (setq p2 (list 100 100))


(atom <item>)

The function gives back nil if item is a list. In all other cases is gives back T. That
means the item is seen as an atom.
Examples:

(setq a '(x y z)) (setq b 'a)


(atom 'a) gives back T (atom a) gives back nil (atom 'b) gives back T (atom b) gives
back T (atom ;(a b c)) gives back nil

(listp <item>)
This function checks whether the item is a list. If so it gives back T. If not it gives
back nil.
Examples:

(listp '(a b c)) gives back T (listp 'a) gives back nil (listp 4.35) gives back nil

(length <list>)
This function gives back the length of the list. It counts the number of elements in
the list.
Examples:

(length '(a b c d)) gives back 4


(length '(a b (c d)) gives back 3
(length '()) gives back 0

(car <list>)

This function gives back the first element of the list. The function may give back an
atom or a list. If the list is empty, then nil is given back

(car '(a b c)) gives back A (car '((a b) c) gives back (A B) (car '() gives back nil

(cdr <list>)

This function gives back a list that contains all element of the list except the first
element of the list.

Examples:

(cdr '(a b c)) gives back (B C) (cdr '((a b) c) gives back (C) (cdr '()) gives back nil

If the list is a dotted pair, then the second element is given back. But the second
element is no longer a list. It is an atom.

(cdr '(a . b)) gives back B (cdr '(8 . "0")) gives back "0"
caar, cadr. cddr, cadar, etc.
We have seen the CAR function and the CDR function. You can combine these two
functions. If you do you quickly isolate an element of the list.

Examples:
(setq x '((a b) (c d))

(caar x) gives back A (cdar x) gives back (B) (cadar x) gives back B (cadr x) gives
back C (cddr x) gives back (D) (caddr x) gives back D

In AutoLISP the CADR function is often used to find the Y value of a point. This is
how a point looks:
(setq pt (list 10 20 0))
Y value is (cadr pt)
(last <list>)
This function gives back the last element of a list.
Examples:
(last '(a b c)) gives back C (last '(a (b c)) gives back (B C)
(member <expression> <list>)

Now there is looked whether the expression is part of the list. If so then the list is
given back starting with the expression.

If the expression is not member of the list, then what is given back is nil.
Examples:
(member 'c '(a b c d e)) gives back (C D E) (member 'q '(a b c d e)) gives back nil
(nth <number> <list>)

With the number argument the number of the element in the list is given back. But
take care. The numbering starts at zero.

If the number argument is more than the highest number of the element in the list,
then nil is given back by the function.

Examples:

(nth 3 '(a b c d e)) gives back D (nth 0 '(a b c d e)) gives back A (nth 5 '(a b c d e))
gives back nil

(reverse <list>)
Now the list is reversed.
Examples:
(reverse '(a b c d)) gives back (d c b a) (reverse '((a b) c d)) gives back (d c (a b))
(assoc <item> <list>)

This function looks in a list from the AutoCAD database for the element that has
the item. If no item is found, then the function gives back nil.

(setq aa '((name carton) (width 100) (height 2000))


(assoc 'width aa) gives back (WIDTH 100) (assoc 'depth aa) gives back nil
(subst <new element> <old element> <list>)

You have a list. You want to change an element of the list with a new element. Use
this function to do that. That is how easy it is.

Examples:
(setq ls '(a b (c d) b))
(subst 'qq 'b ls)
(subst 'qq 'z ls)
(subst 'qq '(c d) ls) (subst '(qq rr) '(c d) ls) gives back (A B (QQ RR)

B)
gives back (A QQ (C D) QQ)
gives back (A B (C D) B))
gives back (A B QQ B)

This function is often used for lists that are found in the AutoCAD database.
Example:

(setq a '((name carton) (width 100) (height 200))) (setq old (assoc 'name a))
(setq new '(name rectangle))
(setq b (subst new old a))

This gives back:


((NAME RECTANGLE) (WIDTH 100) (HEIGHT 200))
(foreach <name> <list> <expression> ...)

The function goes through the list. Every element of the list is evaluated according
to what is said in the expression.
The function gives back the evaluation of the last element of the list. Here is how it
could look:

(foreach n '(1 2 3( (* n 2))


The evaluations are:

(* 1 2) gives 2
(* 2 2) gives 4
(* 3 2) gives 6

In th example the function gives back 6.


(apply <function> <list>)
With the APPLY function you can evaluate the elements of a list.
Examples:

(apply '+ '(1 2 3)) gives back 6 (apply 'strcat '("Auto" "LISP") gives back
"AutoLISP"

(mapcar <function> <list 1> ... <list n>)

The MAPCAR function evaluate the elements of the lists. The function that is
specified is used. What is given back is a list.

Example:

(setq a 10
b 20
c 30\ )

(mapcar '1+ (list a b c)) gives back (11 21 31)


This has been evaluated:

10+1=11
20+1=21
30+1=31

(mapcar '+ '(10 20 30) '(2 3 4)) gives back (12 23 34)
This has been evaluated:

10+2=12
20+3=23
30+4=34

AutoLISP Program

Here is an AutoLISP program. The program makes use of LIST functions that are
described in this paper. This drawing has been created with the AutoLISP
program.
This is what happens. The program asks for the radius of a circle. Next there is
asked for the position of the circle, a description, and a group.

The circle is drawn and the description and the group is placed in the circle.
Another circle can be drawn with a description and a group.

When no more circles are drawn, then lines are drawn between the circles. The
lines are between the circles. In the order that the circles have been drawn.

Here is the program:


(defun c:relpr (/ th pt ds gr ls)
; Settings

(setvar "cmdecho" 0)
(setq rd (udist "Radius circle" rd)) (setq th (/ rd 2))

; Placing circles and texts


(while (setq pt (getpoint "\nPosition circle: "))
(setq ds (getstring "\nDescription: ")) (setq gr (getstring "\nGroup: "))
(if ls

(setq ls (append (list pt) ls)) (setq ls (list pt))


)
(command "circle" pt rd)
(command "text" "m"
(polar pt (* 0.5 pi) (* (/ 2.5 3) th))
th
0
ds
)
(command "text" "m"
(polar pt (* 1.5 pi) (* (/ 2.5 3) th))
th 0 gr )
)

; Processing list and drawing lines (setq p1 (nth 0 ls)


p2 p1
nr 1

)
(while (setq p3 (nth nr ls))

(command "line" (polar p2 (angle p2 p3) rd) (polar p3 (angle p3 p2) rd) ""

(setq p2 p3
nr (1+ nr)
)
)
(command "line" (polar p1 (angle p1 p2) rd) (polar p2 (angle p2 p1) rd) ""
)
(setvar "cmdecho" 1)
)

; UDIST function
(defun udist (tx df / pt)
(if df
(progn
(setq tx (strcat "\n " tx " <" (rtos df 2

2) ">: "))
(initget)
)
(progn

(setq tx (strcat "\n" tx ": "))


(initget 1)

)
)
(setq pt (getdist tx))
(if pt

pt
(setq pt df) )
)
(c:relpr)

Do you see? As circles and texts are placed, the list LS is created. In the list are all
the points used for drawing the circles.

Later in the program, in the Processing list and drawing lines part of the program,
the list LS is used for finding all the points.

Once two points have been found, a line can be drawn. See how all lines are drawn.
Also the line between the last circle and the first circle.

Exercise

Write an AutoLISP function that can be used to change all the system variables. A
lisst of all the fucntions is given to the function.

This is how the function is used:


(smode <list>)

In the list are sub lists. In the sub lists is the name of system variable and the new
value it will get. The old value is known.

The function gives back a list with all the system variables and the old value of the
system variables. The list is used again to restore the values.
Example. Suppose we want to give new values to the CMDECHO system variable
and the BLIPMODE system variable.

This is the line in the AutoLISP program:


(setq md (smode '((“cmdecho” 0) (“blipmode” 0))
What is given back by the function is the following list:
((“cmdecho” 1) (“blipmode” 1))

External Files

AutoLISP makes it possible to communicate with external files. You can read
external files and you can write to external files.

Those files are text files. So everything is done on an ASCII base. But external
Windows programs can read text files that are ASCII files.

(open <file name> <mode>)

With this function an external file is opened to read data from or to write data to.
The function gives back a so called FILE DESCRIPTOR.

You need the FILE DESCRIPTOR if other AutoLISP functions are used to read
data from the file or to write data to the file.

In the argument FILE NAME the name of the external file is mentioned. Also the
extension of the external file is given in FILE NAME.

The MODE argument says if you want to read from the external file or if you want
to write to the external file. This is what MODE can be:

mode description

“r” This MODE stands for “read”. Use it if you want to read from a file. If the file
doesn't exist, then nil is given back.

“w” This MODE stands for “write”. Us it if you want to write to a file. If the file
doesn't exist, then a new file is created.

If the file exists, then the complete file is overwritten by the new data. The data is
not added to the file.

“a” This mode stand for “append”. If the external file doesn't exist, then a new
external file is created.
If the external file exists, then data is added to the file. The data is not used to
overwrite the file.

Examples:
The files in the examples do not exist.
(setq fd (open “new.txt” “w”))
(setq fd (open “old.txt” “r”)) (setq fd (open “log.txt” “a”)) gives back

<File #nnn> gives back


<File #nnn>
gives back nil

The FILE NAME argument can contain the specification of a folder. So the FILE
NAME argument may contain the following information.

“c:/mydocuments/files/new.txt”
That is important. Normal slashes are used. Not back slashes.
(close <file description>)
This function closes an external file that has been opened with the OPEN function.
The file descriptor is given by the OPEN function. (read-char [<file descriptor>])

This function reads one character from the keyboard or from an external file that
has been opened. The function may wait for a key to be pressed.

The function gives back the ASCII value of the character that is read, So if you
click A, B, and C and a RETURN, then this is given

65, 66, 67, and 10. Ten is the ASCII value of the RETURN key.

If the FILE DESCROPTOR argument is present, then one single character of the
external file is read and the ASCII value of that character is given.

Example:
We have the file DATAF.TXT. In the file is written:
prefab concrete clean gray masonry clean light masonry
(setq fd (open “dataf.txt” “r”))

(read-char fd) gives 112 (ASCII number for “p”) (read-char fd) gives 114 (ASCII
number for “r”) (read-char fd) gives 101 (ASCII number for “e”)

The function READ-CHAR works with a pointer. It checks what the last character
was that was read. And takes the next character.
(read-line [<file descriptor>])

This function reads a complete line from the keyboard or out of an external file.
The READ-LINE function also uses a pointer.

When the READ-FILE function comes to the end of an external file, then nil is
given back by the function.

(findfile <file name>)

This function looks for the file name in the AutoCAD folder. The AutoCAD folder
consists of the folder in which is drawn.

It is also the folder from which a drawing has been loaded into AutoCAD or the
folder that is specified in the ACAD system variable.

If the file name argument is found, then the function gives back the name of the file
and the folder in which the file is found.

You can specify a folder using the FILE NAME argument. If you do, the function
only looks in the folder that has been specified.

Example:

(findfile “test.lsp”) gives back “/acad/test.lsp” (findfile “demo.lsp”) gives back


“/bib/demo.lsp” (findfile “drw.dwg”) gives back nil

(write-char <number> [<file descriptor>)


This function writes a character to the screen or to an open file. That is important.
The ASCII code of the character must be given. So (write-char 67) writes C to the
screen. And (write-char 67 fd) writes C to the open file.
(write-line <text> [<file descriptor>)

This function is the same as the previous function. Except now a line is written to
the screen or to an open file.

Example:
(write-line “Text” fd) writes “Text” to the external file.
(princ <expression> [<file descriptor>)

This function acts as the previous function. Something is written to the external file
or the screen. But there is a difference.
Using the WRITE-LINE function only a text can be written tot he external file.
Using the PRINC function any expression can be written to the external file.

You can use the following control codes with the PRINC function:
control description code

\\ the character “\” \e escape


\n new line
\r return
\t tab
\nnn character with the octal code nnn

(prin1 <expression> [<file descriptor>)

This function is the same as the previous function. Except the expression is written
to the external file with double quotation marks.

(print <expression> [<file descriptor>)

The function is the same as the previous function. Except now the new line
character is added to the expression and behind the expression is a space.

AutoLISP Programs

Here is an AutoLISP program that demonstrates how an external file can be read
and how the information of the file can be used.

We have an external file. The name of the external file is LINES.TXT, And these
are the lines that can be found in the LINES.TXT.

prefab concrete
clean masonry, gray
clean masonry, light gray panels, metal

Here is the AutoLISP program. In the program there is asked for the name of the
file. that is to be read. We want the AutoLISP program to read the LINES.TXT file.

That is important. If we give the name of the file, then we must also give the
extension of the file. In our case it is TXT.

And we must specify where the file is located on your hard drive. Let's make that
one easy and copy the file to your root directory.
So when is asked for the file name, you enter:
C:/LINES.TXT
Use a slash and not a back slash.

(defun c:rtext (/ nm pt fd tx)


(textscr)
(setq nm (getstring "\nFile name: ")

pt (getpoint "\nStarting point: ") th (udist "Text height" th) ra (udist "Line
distance" ra) fd (open nm "r")

)
(while (setq tx (read-line f))
(command "text" pt th 0 tx)
(setq pt (polar pt (* pi 1.5) ra))
)
(close fd)
(command "zoom" "all")
(command "zoom" "0.8x")
(princ)
)

(defun udist (tx df / pt)


(if df

(progn
(setq tx (strcat "\n " tx " <" (rtos df 2 2) ">: "

)
)
(initget)

)
(progn
(setq tx (strcat "\n" tx ": ")) (initget 1)
)
)
(setq pt (getdist tx))
(if pt
pt
(setq pt df)
)
)

(c:rtext)

Here is an AutoLISP program that demonstrates how text can be written to an


external file. We use the LINES.TXT file that we have.

The LINES.TXT file is in the root directory. As you can see. It is specified in the
AutoLISP program. See how the AutoLISP program works.

(defun c:wtext (/ fd md tx)


(initget "Add Replace")
(setq md (getkword "\nAdd/Replace: ")) (cond

((= md "Add")
(setq fd (open "c:/lines.txt" "a"))
)
(T
(setq fd (open "c:/lines.txt" "w")) )
)
(while (/= (setq tx (getstring "\ntx: ")) "") (write-line tx f)
)
(close fd)
(princ)
)

(c:wtext)

Exercise

For this exercise you are going to work with an external file. Using the external file
the following drawing is created.
This is what is found in the external file:

WD TH R1 R2

20 3 2 3.5
35 3 2 5
39 3 2.5 6
40 4 3 6

The user is asked to enter the width of a profile. In the external file the width can be
found. And the other sizes are found there.

AutoLISP And AutoCAD Database

AutoCAD has got a database. In the database a lot of information is stored.


IntelliCAD has got the same database.

That is so good. Through AutoLISP we have access to the AutoCAD database. And
we can make changes to what is in the AutoCAD database.

Here we are going to give further information about the AutoCAD database. We
are also going to talk about all the functions that can be used.
AutoCAD Database

The AutoCAD database consist of five sections:


1. Header

This section contains all the information that has got to do with the drawing, such
as system variables.

2. Tables
This section contains definitions of the following:

- Line types
- Layers
- Text styles
- Views
- User Coordinate System
- View port configuration
- Drawing manager

This section contains information about the contents of blocks


4. Entities

This section contains all the information about the entities that have been drawn
and it also contains information about blocks.

5. End of file
This section indicates where the AutoCAD database ends.

Entities

An entity is any object that has been drawn in a drawing. An entity can be a:

- line
- circle
- arc
- polyline
- text
- solid
- point
- etc.

The information of a line in a database contains among other things:


- Layer on which it is drawn
- Color
- Start point
- Endpoint
- Line type

Her is the information of a line in the database:

((-1 . <Entity name: 3424828>) (0 . “LINE”) (5 . “1C4”) (67 . 0) (8 . “0”) (62 . 256) (6
. “ByLayer”) (370 . -1) (347 . <Entity name: 0>) (284 . 0) (48 . 1.00000) (60 . 0) (39 .
0.000000) (10
-23.7433 3.15412 0.000000) (11 33.0641 25.6152 0.000000) (210 0.000000 0.000000
1.00000))

The information is stored in a list. In the list you find a lot of dotted pairs. Later we
will explain where the dotted pairs stand for.

The list is called an entity list. You can change the entity list. For instance. If you
have a line, you could change the color of the line.

Database Structure

Every entity gets a name during the drawing session. It gets a so called entity name.
This name is given to each entity as the drawing is loaded.

If you close the drawing and later loads it again. New entity names are given to all
the entities of the drawing . So the names changes all the time.

Not so the handles. Every entity has got a handle too. That is a number too. The
handle of an entity never changes. It is always the same.

We have seen the entity list of a line. You see the entity name in the entity list. Here
it is.
<Entity name: 3424828>

Looking at the entity name, you cannot see what type of entity you are dealing with.
It could be a line, a circle, an arc, etc.

In the entity list you find information about the entity. The information is stored in
dotted pairs or sub lists.

Every sub list starts with a number for a code. The number tells what is the
function of the dotted pair. Here are some examples:

Code Meaning

-1 entity name 0 entity type 8 layer of entity 10 start point of entity 11 endpoint of
entity

The second part of the dotted pair depends on the code. If the code is 8, then the
second part is the layer name in quotation marks.

There are two types of functions that can be used to get information from the
AutoCAD database:
1. Entity functions
2. Selection set functions

Entity functions

(entnext [<entity name>])

If this function is sued without the entity name as an argument, then the function
gives back the name first entity of the drawing.

If the function is used with an entity name as argument, then the entity coming
after the mentioned entity name is given back.

(entlast)
This function gives back the name of the last entity in the drawing.
(entsel [<prompt>])

This function asks the user to select an entity in the drawing. The prompt is
displayed if it is there. If not then the “Select entity:” prompt is displayed.

The function gives back a list with in it the entity that has been selected and the
point where the entity is

selected.
Example:
(entsel)
Given back:
(<Entity name: 3690540> (-2.59161 18.7661 0.000000))

If you want to find what entity is selected, then the CAR function is used. For
finding the selection point, the CADR function is used.
You can use the OSNAP function to get a point that is laying on the entity.
(redraw [<entity name>] [<mode>])

This function can be used in three ways. You can use it without arguments, you can
use it with an entity name, and you can specify a mode.

If used without arguments, then a REDRAW is performed in the active view port of
AutoCAD. The REFRAW is the same as the REDRAW command of AutoCAD.

When an entity name is given as an argument of the REFDRAW function, then the
entity is redrawn. Only the entity is redrawn.

The REDRAW function has got four modes. These are the modes:
Mode Meaning

1 Redraw entity in the screen


2 Makes the entity invisible
3 Highlights the entity in the screen
4 Shows the entity in normal view

Selection set functions

(ssget [<mode>] [<point 1>] [<point 2>])

With this function one or more entities can be selected. What is given back by the
function is a selection set.

The entity or the entities that have been selected are in the selection set. And what
entities are in the selection set. That can be found.

But there is more to this function. The function can be used without any arguments.
If you do, then the following prompt is displayed:
Select entities:

That prompt is displayed again and again until the right mouse button is clicked or
the RETURN key is pressed.

You can select entities in the AutoCAD drawing. But what is given back by the
function is a selection set.

What is selected is in the selection set.

But the SSGET function has got modes. Depending on eh mode that is used, one or
two points are also entered as argument.

These are the modes of the SSGET function:


Mode Description
“P” The previous selection set is selected.
“L” The last entity of the drawing is selected.
Point The entity going through the point is selected.

“W” Two points are used as argument for the function. With the points a window is
specified. And what is in the window is selected.

“C” Again two points are used as argument for the function. The points specify a
crossing. What is in the crossing and touched by the crossing is selected.

“X” Now no points are used as argument. A filter list is added as argument. All
entities that are conform the filter list are selected.

AutoCAD is using a temporary database for storing the values of the selection set.
That is why no more than six selection sets can be created.

(ssget “x” <filter list>)

We already have seen how this function is sued. We saw it as we were talking about
the SSGET function. Here is an example.

Suppose we want to select all the entities that have the color red. We need to create
a dotted pair that is used for the color red.

We know. The code for color is 62. And the number of the color red is 1. So to
create the dotted pair we use:

(cons 62 “1”)
That will give back:
(62 . 1)
To select all entities with the color red we use the SSGET function like this:
(setq ss (ssget “x” (cons 62 “1”)))
Here is a list of codes that can be used. There are much more codes.
Code Description

0 Entity type
2 Block name
6 Linetype name
7 Text style name
8 Layer name
38 Elevation
39 Thickness
62 Color
66 Attribute number
210 3D extrusion

Here is another example. We want to select all entities that are a line, that are on
the layer WALLS, and that have the color BYBLOCK.

(setq ss (ssget “x” (cons 9 “LINE”) (cons 8 “WALLS”) (cons 62 “0”))


(sslength <ss>)
This function tells us how many entities can be found in the selection set.
(ssname <ss> <index>)

With this function you can get the entity name of an entity in the selection set. You
must specify an index number to get the name.

That is important. The index number of the first entity in the selection set is zero.
When no entity is found, then nil is given back.

(ssadd [<entity name>] [<ss>])

You have a selection set. And you want to add an entity to the selections set. You
can do it using the SSADD function.

(ssdel >entity name> <ss>)

Now you have a selection set. In it is an entity that you ant to remove from the
selection set. Use this function for doing that.

(ssmemb <entity name> <ss>)

This function tests if the entity is part of the selection set. If so, then the name of the
entity is given back. Otherwise nil is given back.

AutoLISP Program

Here is an AutoLISP program that uses the ENTSEL, CAR, ENTGET, CDR,
ASSOC functions to get information about the block that is selected.

(defun c:place ()
(setvar "cmdecho" 0)
(setq sl (entsel "\nSelecteer block: ") et (car sl)
el (entget et)
tp (cdr (assoc 0 ed))

)
(cond
((= tp "INSERT")

(setq bn (cdr (assoc 2 el))


ip (cdr (assoc 10 el))
)
(command "insert" bn
(polar ip (/ pi 4) 50) 1
1
0
)
)
)
(command "zoom" "all")
(command "zoom" "0.8x")
(setvar "cmdecho" 1)
(princ)
)

(c:place)

Here is an other AutoLISP program. You could say. This is a different version from
the AutoCAD scale command. Now it is automated.

If you use the scale command of AutoCAD, then you must pick a point for scaling.
You must also enter an X value and an Y value.

Using this AutoLISP program that is not needed. You select a block and the block
is scaled right away over its insertion point.
See what AutoLISP functions are used here.

(defun c:newsc (/ ss os ns os fc ct ln et el tp ip) (princ "\nSelect a block to scale: ")


(setq ss (ssget))
(if ss

(progn
(setq os 1
ns (getdist "\nNew scale factor: ") os (getdist "\nOld scale factor: ") fc (/ ns os)
ct 0
ln (sslength ss1)

)
(while (< ct ln)

(setq et (ssname ss ct)


el (entget et)
tp (cdr (assoc 0 el))

)
(if (= tp "INSERT")

(progn
(setq ip (cdr (assoc 10 el))) (command "scale" en "" ip fc) (redraw)

)
)
(setq ct (1+ ct))

)
)
)
)
(c:newsc)

Entity Data Functions

(entdel <entity name>)

With this function an entity is removed from the AutoCAD database. Or it is put
back in the AutoCAD database if it has been removed earlier.

Example:

(setq et (entlast)) (entdel et)


(entdel et)

With the first line the last entity is given the name ET. Next the ENTDEL function
is used to remove the entity from the database.

When removed from the database, the entity is also deleted from the screen. In the
last line the entity is pout back in the database.

(entget <entity name>)


With this function the entity list of an entity is found and given back.
Example:

Suppose we have a line that is drawn in the layer WALLS from point 2,2 to point
6,6. This is what is give back by the ENTGET function:

((-1 . <Entity name: 3964828>) (0 . "LINE") (5 . "1C4") (67 . 0) (8 . "WALLS") (62


. 256) (6 . "ByLayer") (370 . -1) (347 . <Entity name: 0>) (284 . 0) (48 . 1.00000) (60 .
0) (39 . 0.000000) (10 2 2 0.000000) (11 6 6 0.000000) (210 0.000000 0.000000
1.00000))
Do you see where the name of the layer can be found? It is found in the sub list with
the code number 8. And the start point and the end point?

The start point can be found in the sublist with the code number 10 and the end
point can be found in the sub list with the code number 11.

(assoc <code number> <entity list>)

We want to find what is in the sub list of an entity list. Use this function. In it
specify the code number of the sub list and the entity list.

The function gives back a dotted pair. Let's take the entity list that was found using
the previous example. This is how it looks:

Assoc Gives back:

(assoc 0 el) (0 . "LINE")


(assoc 8 el) (8 . "WALLS")
(assoc 38 el) nil
(assoc 10 el) (10 2.0000 2.0000 0.0000)

Using the CAR and CDR function you can find the first and the second element of
the sub list or the dotted pairs. Example:

CAR/CDR Gives back:


(car (0 el)) 0
(cdr (10 el)) (2 2 0.000000)
(cons <first element> <second element>)

This function is used to create a new dotted pair or list. The first element can be a
list or an atom. The same goes for the second element.

Examples
Function Gives back
(cons 8 "FLOOR") (8 . "FLOOR") (cons 10 '(10.0 10.0) (10 10.0000 10.0000)
(subst <new item> <old item> <list>)

The function looks for the old item in the list and replaces it with the new item. If
the old item is not found., then the original list is given back.

Example:
(setq ls '(a b (c d) b)
Function

(subst 'qq 'b ls) (subst 'qq 'z ls) (subst 'qq '(c d) ls) (subst '(qq rr) (c d) ls) (A B (QQ
RR) B) Given back

(A QQ (C D) QQ) (A B (C D) B) (A B QQ B)

(entmod <entity list>)

With this function an entity list is written back to the AutoCAD database. This is
making the AutoCAD database up to date.

The ENTMOD function has got a limitation. You cannot change the sub list with
the code number zero and the sub list with the code number 5. The sub list with the
code number zero stand for the type of the entity. And the sub list with the code
number 5 stand for the handle of the entity.

All parts such as text style, line type, shape, and block should be specified before
they can be used by the ENTMOD function.

The ENTTMOD function checks whether the entity list that is send to the
AutroCAD database is valid. If not, then the AytoCAD database is not updated.

(entupd <entity name>)

When the ENYMOD function is used, then the entity is changed in the screen.
Suppose you have changed the color of the entity.

If so, the color of the entity will change. The entity will get the new color. But. That
will not always work. It doesn't work with polylines and blocks.
That is why the ENTUPD function must be used for complex entities. The ENTUPD
function updates even complex entities in the screen.

Symbol Tables

In the AutoCAD database you find tables. With AutoLISP you can find what is in
the tables. But you cannot change what is in the tables.

In the AutoCAD database you find the following tables:

• Linetypes
• Layers
• Text styles
• Views
• User Coordinate System
• Viewport configuration
• Blocks

The following functions can be used for searching the tables.


(tblnext <table name> <begin>)

Using this function you can go through a symbol table.


The first argument of the function is the table name. We have the following table
names:

• ”LAYER:
• ”LTYPE”
• ”VIEW”
• ”STYLE”
• ”BLOCK”
• ”UCS”
• ”VPORT”

The TBLNEXT function has got its own pointer. So it knows what was the last
entry that was read from the table. And if used again, the following entry is taken.

If the end of the symbol table has been reached, then nil is given back by the
function. Normally a dotted pair is given back by the TBLNEXT function. (tblnext
“layer” T)

This my give back:


((0 . “LAYER”) - symbol table (2 . “0”) - symbol name (70 . 0) - flags (62 . 7) - color
number (6 . “CONTINUOUS”) - line type

The color an the line type is given to the entity that is drawn on the layer. If the
entity is drawn in BYLAYER mode.

Suppose we have a table that is called FRAME. We go through the LAYER symbol
table. This is what is given back by the function.

(tblnext “block”)
This is given back:

((0 . BLOCK)
(2 . FRAME) \(70 . 0)
(10 100.0000 100.0000) (-2 <Entity name: 40000136)

)
(tblsearch <table name> <symbol> <follow>)

With this function you can search in a symbol table for a symbol. When the symbol
is found, then a dotted pair is given back.
(tblsearch “style” “standard”)

could give back

((0 . “STYLE”) - name of the symbol table (2 . “STANDARD”) - name of the


symbol (70 . 0) - flags
(40 . 0.0) - text height
(41 . 1.0) - width factor
(50 . 0.0) - oblique angle
(71 . 0) - generation flags (3 . “txt”) - “font file”
(4 . “”) - “bigfont file”

The pointer of the TBLSEASRCH function has no effect on the pointer of the
TBLNEXT function, unless the follow argument is present and unequal to nil.

Handles

Every entity in AutoCAD has got a specific identification code. This code is called a
handle and changes all the time.

The handle always is connected to the entity and never changes. Not even if the
drawing is closed and later opened again.

The handles are generated by AutoCAD. You cannot change the handles. You
cannot create your own handles.
Using AutoLISP you can read what is the handle of an entity. You can store the
handles in an external database or so.

A line can have the following entity list

((-1 . <Entity name: 3964828>) (0 . “LINE”) (5 . “1C4”) (67 . 0) (8 . “0”) (62 . 256) (6
. “ByLayer”) (370 . -1) (347 . <Entity name: 0>) (284 . 0) (48 . 1.00000) (60 . 0) (39 .
0.000000) (10
-23.7433 -5.60872 0.000000) (11 32.9634 25.0109 0.000000) (210 0.000000 0.000000
1.00000))

In the example the handle of the line is 1C4.


(handent <handle>)

We have the handle of an entity. Use this function to ding the name of the entity.
This function gives back the name of the function.

Example:
We have seen the entity list of the line. We call it EL. This is what we do.
(setq hd (cdr (assoc 5 el))) (setq et (handent hd))
The entity name of the line is given back. You can work with it further.

Exercise

Create an AutoLISP program that places a valve in a line. See the drawing for how
it looks. There is a line in eh drawing and the valve is placed in the line.

Here are some tips.

• Create a block that is the valve.


• The block has got an insertion point and it has got a point at the right.
• The insertion point is in the middle of the block.
• Look in the blocks table for the block. Find the point and find the insertion point.

The point and the insertion point help to find the opening of the line.
Exercises

1. Draw a circle in the screen. And find the following information:

- The entity name of the circle.


- The handle of the circle.
- The layer of the circle.
- The center point of the circle.
- The radius of the circle.

2. Draw five circles in the screen. Select them all using the SSGET function. Use the
window mode and the crossing mode.

3. Open a drawing in AutoCAD, Any drawing. Find the following information


about the drawign:

- The names of all layers.


- What line types have been used.
- What blocks can be found in the drawing.

System Management

Here we are going tot talk about system management with regard to AutoLISP
functions. That has got to do with the limited memory of AutoLISP.

AutoLISP Memory

The maximum memory of DOS is probably 640K. Only 128K is used by AutoLISP,
83K by the AutoLISP program. The rest is for the programs and data.

The AutoLISP memory is divided in Heap and Stack. This is what can be found in
the Heap and the Stack
Heap Stack

AutoLISP functions Function arguments Symbols Temporary results Self defined


functions Temporary data
AutoLISP pointers Text area
Node space Program counters
Data

The division of the Heap and Stack is set by the LISPHEAP system variable and the
LISPSTACK system variable. Their total is 45.000.
In general those two variables are set as:
LISPHEAP 40,000
LISPSTACK 5.000

This means that you must use your AutoLISP memory very efficient. There are a
couple of rules. Here they are:
- Keep variables local if you can.

- Standardize the names of variables. Use the same name all the time.
- Set the value of the variables to nil if they are not used.
- Give variables a name of two characters.
- Give programs a name of five characters

- Functions that are used once, use them at the start of the AutoLISP program. Use
the LAMBDA function for doing that.

- When the LAMBDA function is used, the use of the stack memory is minimal.
- Only load functions that are truly needed.

- Use the same name of large functions. If that is done, then the memory for those
functions is replaced.

You can still get the following two warnings:


- error: insufficient node space
- error: insufficient string space
If those error messages occur, then you have the following options:

1. Use the so called CLEAN effect to remove unused functions from the memory.
2. Increase the amount of the Heap memory by using the VCMON function

3. Increase RAM. That is the most expensive option.

The CLEAN Effect

You can easily remove functions and variables from the memory by giving them a
value if nil, Here is an example. Suppose you have the program BLINE.LSP.

Use the following line to set the value of the program to nil:
(setq c:bline nil)

The node space that is used by the AutoLISP program is now set free and can be
used by other AutoLISP programs, functions, and variables.
Here is a program that can be used to make use of the clean effect:

(defun c:clean ()
(setq atomlist member 'c:clean atomlist) (princ)

The VMON Function

This function is not very clear. It must be used before an AutoLISP program is
used in AutoCAD. It is placed in the ACAD.LSP file.

Through the function the virtual function page is activated. When no more node
space, then the program is automatically written to a temporary file.

When the program is used again, then it is taken from the temporary file and used.
This how the VMON function is used.

(VMON)

ACAD.LSP

In the directory or the folder of AutoCAD you find the ACAD.LSP file. IntelliCAD
works with the ICAD.LSP file.
It works the same.

When you start AutoCAD, then the ACAD.LSP file is automatically loaded into the
AutoCAD program. All AutoLISP programs in the file are loaded.

This is the use of the ACAD.LSP file:

- Loading of often used AutoLISP programs and functions.


- Setting of global variables, constants, and AutoCAD system variables.
- Directly evaluate certain AutoLISP expressions.
- Giving information to the user of AutoCAD.
- Going through certain AutoCAD commands.
-
Redefine certain AutoCAD commands such s END. QUIT, and STYLE.

Startup Program

When an AutoLISP program is placed into the ACAD.LSP file, the program is not
automatically running as AutoCAD starts.

The AutoLISP program is loaded into AutoCAD. And a command must be given to
have the program run. But you can have the program run automatically.

Change the name of the program in S::STARTUP and the program will run as
AutoCAD is started. S::STARTUP has no arguments.

Lambda Function

(lambda <arguments> <expression> ...)

The LMBDA fucntion is used when a fucntion is not really necessary. The
LAMBDA fucntion is used together with the APPLY fucntion or the MAPCAR
function.

Here are two examples:

(apply '(lambda (x y z) (* x (- y z)))


'(5 20 14)

)
gives 30
(setq ct 0)
(mapcar '(lambda (x)

(setq ct (1+ ct)) (* x 5) )


'(2 4 -6 10.2)

)
gives (10 20 -39 51.0)

The LAMBDA contention is written in the listing of an AutoLISP program and it is


performed as it is found.

Errors

If there is an error in an AutoLISP program, then an error notification is given.


That helps the programmer to find the error in the program.

For a user of the AutoLISP program an error notification is no good. He or she


doesn't know what to do with the error. Most probably.
In AutoLISP you can have an ERROR function. The function activates when an
error occurs. And then certain actions are taken.

The error function could look like this:

(defun error (tx)


(princ “\nError: “) (princ tx)
(princ)

In the example function the user is told what was the error. But the error function
can also be used to make changes to the settings of AutoCAD.

This is what the ERROR function can do:

- Set back system variables to its original value.


- Switching back to the original layer of the AutoCAD drawing.
- Performing an UNDO action.
- Telling the user what was the error.
-
Writing the error to an external file.

Exercise

For the exercise of the “Parametric Drawing” lesson we have created an AutoLISP
program for drawing a shaft.

Now change the ACAD.LSP file so that that program automatically starts every
time that AutoCAD is started.

System Variables

We have been talking about system variables There are many system variables in
AutoCAD. Her is a list of all the system variables.

There is said what type of system variable the system variable is. And the meaning
of the system variable is given too.

System Variable Type Meaning


ACADVER text Gives version number of the program
AFLAGS integer Gives the setting of the attributes:
1 - invisible
2 - constant
3 - verify
4 - preset

ANGBASE real Gives the angle of the zero angle


ANGDIR integer Angles are measured in the

direction of the clock (1) or against the direction of the clock (1). By default the
value is 1.

APERTURE integer The height of the target


AREA real Gives the last found area. Read only.

ATTDIA integer If the value of this system variable is 1, then a dialog box is
displayed as the INSERT prompt is displayed. Otherwise there are only prompts.

ATTMODE integer Says how attributes are displayed in the drawing:

0 - off
1 - normal
2 - on

ATTREQ integer If the value is zero, then attributes get a default value as a block
is inserted. If the value is 1, then there is asked for the value, depending on the
setting of the ATTDIA system variable.

AUNITS integer Gives the setting of the drawling units:

1 - decimal degrees
2 - degrees/minutes/ seconds
3 - degrees (400)
4 - radians
5 - wind directions

AUPREC integer The number of decimals of angles


AXISMODE integer Indicates whetehr axis ar on (1) or off (0)
AXISUNIT point Gives the horizontal and vertical setting of the axis
BACKZ real Has got to do with the viewport
BLIPMODE integer Indicates whether blips are on (1) or off (0)
CDATE real Gives the current date (read only)
CECOLOR text The color of new entities (read only)
CELTYPE text The linetype of new entities (read only)
CHAMFERA real The first CHAMFER distance
CHAMFERB real The second CHAMFER distance
CLAYER text The current layer (read only)
CMDECHO integer Prompts are displayed in the screen (1) or not (0)
COORDS integer The value can be:

0 - the coordinates only change if a point is picked in the screen

1 - the coordinates change is the mouse if moved


2 - there is asked for a distance when there is asked for it

CVPORT integer The identification number of the active viewport


DATE real The Julian date
DISTANCE real Last measured distance with the DIST command
DRAGMODE integer 0 - off
1 - on
2 - automatic
DRAGP1 integer Check for new coordinates when dragging
DRAGP2 integer Same
DWGNAME text Name of the drawing (read only)
DWGPREFIX text Drive and folder where the drawing is (read only)
ELEVATION real The value of elevation
EXPERT integer About all the “Are you sure” prompts and similar prompts.

0 - all prompts are


displayed
1 - suppresses all prompts
2 - suppresses for prompts of BLOCK command
3 - suppresses prompts of the LINETYPE
command
4 - suppresses all other commands

EXTMAX point

Upper right corner of the drawing. Changes after entities are added to the drawing
and the ZOOM ALL command is given

EXTMIN point This is the lower left corner


FILLETRAD real

The default value of the radius of the FILLET command


FILLMODE integer Fillmode on (1) or off (0)
FLATLAND integer Has got the do with drawing in 3D
FRONTZ real Has got to with the viewport
GRIDMODE integer Grid is on (1) o off (0)
GRIDUNIT point Size of the grid units (x, y)
HANDLES integer Handles are on (1) or off (0)
HIGHLIGHT integer Selected entities are highlighted if 1. Or not if the value is 0
INGBASE point Insertion base point LASTANGLE real The end angle of the last
arc
LASTPOINT point The last point to which a reference can be made using the @
character
LASTPT3D point The same as before, but now it is used for 3D drawings
LENSLENGTH real Length of the lens
LIMCHECK integer Limits check is on (1) or off (0)
LIMMAX point Upper right corner of the limits
LIMMIN point Lower left corner of the limits
LTSCALE real Line type scale factor
LUNITS integer Drawing units mode

1 - scientific
2 - decimal
3 - engineering
4 - architectural

LUPREC integer Number of decimal places


MENUECHO integer Used when menu is in the screen
MENUNAME text Name of the menu that is used with the drive and the folder
MIRRTEXT integer If zero. Than the text is not

displayed mirrored.
Otherwise the text is
mirrored

ORTHOMODE integer Orthomode is on (1) or off (0)


OSMODE integer Object snap mode, could be the sum of the numbers

1 - endpoint
2 - midpoint
4 - center
8 - node
16 - quadrant
32 - intersection 64 - insertion 128 - perpendicular 256 - tangent
512 - nearest
1024 - quick

PDMODE integer Indicates that points in the drawing are made visible
PDSIZE real Size of points in the drawing
PERIMETER real

The circumference as found by the AREA, LIST, or DBLIST command

PICKBOX integer Height of the object selection box in pixels


POPUPS integer If one, then dialog boxes and so are displayed
QTEXTMODE integer Quick text mode is on (1) or off (0)
REGENMODE integer Regenauto is on (1) or off (0)
SCREENSIZE point The size of the graphical screen in pixels (read only)
SKETCHING real The size of generated lines
SKPOLY integer The SKETCH command generates lines (0) or polylines (1)
SNAPANG real Snap/grid rotation angle
SNAPBASE point Snap/grid base point
SNAPISOPAIR integer The active isometric area

1 - Left
2 - Above
3 - Right

SNAPMODE integer Snap in on (1) or off (0)


SNAPSTYL integer Gives what snap style you have:
1 - standard 2 - isometric
SNAPUNIT point Gives the size of the snap. X and Y
SPLFRAME integer If this is set to one, then:

– the control polygon is shown

– only the defined mesh is shown


– invisible faces of 3D faces are shown

– the control polygon of the spline is not shown


– the defined mesh of a polygon is not shown


invisible sides of 3D faces are not shown

SPLINESEGS integer The number of line segments that are generated for each
spline path

SPLINETYPE integer Type of the spline arc generated with the PEDIT command

5 - quadratic B-spline surface


6 - cubic B-spline surface
8 - Bezier surface

SURFTAB1 integer Number of segments

generated with RULESURF and TABSURF. Also mesh thickness in the M


direction

SURFTAB2 integer Mesh thickness in the N direction


SURFTYPE integer Type of the generated surface using the PEDIT command

5 - quadratic B-spline surface


6 - cubic B-spline surface
8 - Bezier surface

SURFU integer Surface thickness in M direction


SURFV integer Surface thickness in N direction
TARGET 3D point Location of the target of the active viewport
TDCREATE real Time and date of the drawing (read only)
TDINDWG real Total time used for creating the drawing
TDUPDATE real Time and date of the last update
TDUSRTIMER real Timer that is running as a drawing is created
TEMPPREFIX text Folder where temporary drawing files are stored
TEXTEVAL integer Has got to do with how texts are read and understood
TEXTSIZE real The height of the text if the text style has got a set height
TEXTSTYLE text The text style (read only) THICKNESS real The set thickness
TRACEWID real The trace thickness
UCSFOLLOW integer Every change of the UCS changes the view if one. If zero no
change
UCSICON integer Is about the UCS icon

0 - off
1 - on
2 - UCS is in the source of the active UCS

UCSNAME text Name given to the UCS


UCSORG 3D point Source of the UCS
UCSXDIR 3D point X direction of UCS
UCSYDIR 3D point Y direction of UCS
USERI1-5 integer Five system variables where the use can enter integer values
USERR1-5 real As before. Now real values can be entered
VIEWCTR point Center of the drawing area
VIEWDIR 3D point View direction of the UCS
VIEWMODE integer Viewing bit mode (read only). It is the sum of:

1 - perspective view is active


2 - front clipping is on
4 - behind clipping is on
8 - UCS follow mode is on 16 - front clipping not at height eye

VIEWSIZE real The height of the view (read only)


VIEWTWIST real Viewtwist angle
VPOINTX real X component of 3D viewpoint
VPOINTY real Y component of 3D viewpoint
VPOINTZ real Z component of 3D viewpoint
VSMAX point Upper right corner of the view
VSMIN point Lower left corner of the view
WORLDUCS integer Same as the UCS

WORLDVIEW integer Has got to with the DVIEW and VPOINT command

Working With System Variables In AutoLISP

AutoLISP has got two functions for working with system variables. Those functions
are:
- GETVAR
- SETVAR

Let's say you have the system variable ACADVER and you want to know the value
that is in the system variable.

In your AutoLISP program write:


(getvar “acadver”)
What is given back you can store in a variable. So you could write:
(setq vl (getvar “acadver”))

Suppose you want ti change the value of a system variable. You can change the
value of a system variable if it is not read-only.
Suppose you want to store the value 10 in the USERI1 system variable. This is how
you do it in an AutoLISP program.

(setvar “useri1” 10)

Exercise

We have the ATTDIA system variabel. Check the value of that system variable.
And change it so that it gets the opposite value.
So if the value of that system variable is one, then the new value will be zero. If it is
zero, then the new value will be one.

Dimension System Variables

There are many dimension system variables. But you can set the dimension
variables over the menu of AutoCAD. Or IntelliCAD.

Here is how it is done in IntelliCAD. In the second row of the screen is the menu. In
it click on Dimension. A pop-up menu show up.

In the pop-up menu click on Style. The Dimension Settings dialog box is displayed.
It has eight tabs. Click on them to set the system variables.

I will not mention all the dimension variables. You don't need to know them. You
can set them all over the Dimension Settings dialog box.

DXF Table

LN - Line
PT - Point CI - Circle AR - Arc
TR - Trace SD - Solid TX - Text
3F - 3DFace SH - Shape SQ - Sequend IN - Insert AD - Attdef AT - Attrib PL -
Polyline VT - Vertex DM - Dimension
Code Description Entities
LN PT CI AR TR SD TX SH IN AD AT PL VT DM 3F SQ

-1 Entity name (primary) X X X X X X X X X X X X X X X X


-2 Entity name (secondary) X 1 Primary text value X X X X 2 Name: shape, block, tag X X X X X 3 Text
prompt X

5 Handle (hexadecimal) X X X X X X X X X X X X X X X X
6 Name line type X X X X X X X X X X X X X X X X Text style name X X X X X X X X X X X X X X X X
8 Layer name X X X 10 X start insert point X X X X X X X X X center point X X
X angle point X X X X X definition point X X elevation point (2D poly) X 11 X end insert point X
X angle point X X X X alignment point X X X X midpoint dimension X 12 X angle point X X X X insert point X
13 X angle point X X X X definition point X 14 X definition point X 15 X definition point X 16 X definition
point X

20 X start insert point X X X X X X X X X center point X X X angle point X X X X definition point X X


elevation point (2D poly) X

21 X end insert point X


X angle point X X X X alignment point X X X X midpoint dimension X

22 X angle point X X X X insert point X


23 X angle point X X X X insert point X
24 X definition point X
25 X definition point X
26 X definition point X
30 X start insert point X X X X X X X X X center point X X
X angle point X X X X definition point X X elevation point (2D poly) X
31 X end insert X
X angle point X X X X alignment point X X X X midpoint dimension X
32 X angle point X X X X insert point X
33 X angle point X X X X definition point X
34 X definition point X
35 X definition point X
36 X definition point X
38 Entity elevation X X X X X X X X X X X X X X
39 Entity thickness X X X X X X X X X X X X X X
40 Radius X X
Height, width X X X X X X Leader length X
41 X scale factor width X X X X X X X
42 Y scale factor bulge X X
43 Z scale factor X
44 Column spaces X
45 Row spaces X
50 Rotation angle X X X X X X X Start angle X
Curve fit tangent X
51 End angle X
Skew angle X X X X Horizontal angle X
62 Color X X X X X X X X X X X X X X X X
66 Entity follow flag X X
70 Dimension type X Flag poly line vertex X X Attribute flag X X Column counter X
Invisible rand flag X
71 Text generation flag X X X Row counter X
Mesh M counter X
72 Text alignment X X X Mesh N counter X
73 Field length X X Surface M density X
74 Surface N density X
75 Surface type X 210 X extrusion point X X X X X X X X X X X X X X X 220 Y extrusion point X X X X X X
X X X X X X X X X 230 Z extrusion point X X X X X X X X X X X X X X X

Exercise

Here is the entity list of a line:


((-1 . <Entity name: 3694828>) (0 . "LINE") (5 . "1C4") (67 . 0) (8 . "0") (62 . 256)
(6 . "ByLayer") (370 . -1) (347 . <Entity name: 0>) (284 . 0) (48 . 1.00000) (60 . 0) (39
. 0.000000) (10
-25.2541 24.2051 0.000000) (11 32.5605 -10.4434 0.000000) (210 0.000000 0.000000
1.00000))

You see all the parts of the list and you see the codes that are in the parts of the list.
Find out where all the codes stand for.

Here is the entity list of a circle. Do the same with this entity list.

((-1 . <Entity name: 3790540>) (0 . "CIRCLE") (5 . "1C5") (67 . 0) (8 . "0") (62 .


256) (6 . "ByLayer") (370 . -1) (347 . <Entity name: 0>) (284 . 0) (48 . 1.00000) (60 .
0) (39 . 0.000000) (10 51.7984 22.5935 0.000000) (40 . 12.4260) (210 0.000000
0.000000 1.00000))

Final Words

How you have got an e-book that is an AutoLISP course. Now you have seen how
programming in AutoLISP is done.

It is not too complicated. There are not too many functions. But still. You may be
wondering. Is programming in AutoLISP hard?

I have written an e-book about programming in AutoLISP. The e-book is called


“AutoLISP Programming Is Easy”.

In the e-book I explain how AutoLISP programming is done. There is an example


AutoLISP program in the e-book. The program says it all.

If you want to have the e-book. Go to my newsletter. You find my newsletter here:
http://groups.yahoo.com/group/makeautocadfast
You must subscribe to my newsletter. After your subscription the e-book will be
send to you.

Oh. If you subscribe to my newsletter, you will also get an AutoLISP program that
automatically creates a complete AutoCAD drawing.

And you will get a report about External Files. You will get that file too after you
subscribe to my newsletter.

I have a newsletter. I also have a blog. It is the Make AutoCAD Fast blog. You can
find my blog on this website address:

http://josvandoorn.freeblog.biz/

Good luck with AutoLISP programming. If you have any question or maybe you
want to say something to me. Send me an e-mail. This is my e-mail address:

mailto:makeautocadfast@ymail.com

You might also like