Autotlisp - Programming Notes
Autotlisp - Programming Notes
7 AutoLISP Programming
AutoLISP is a high, level interface language for AutoCAD, It is a derivative of the LISP
(List Processing) programming language developed by John McCarthy at MIT in
1960 and used mainly for Artificial Intelligence. AutoLISP allows users of AutoCAD
to write macro-programs and functions that are well suited for graphics applications.
Where there is more than on operator, these are separated by brackets or parenthesis.
e.g. (a x b) + (d/c) will be written in LISP as (+ (* a b)(/ d c))
setq is the function used for assigning values to variables. It is equivalent to the - sign.
For example: a = 5 is written in LISP as
(setq a 5)
FORTRAN and PASCAL, that are procedural, AutoLISP is a functional list processing
language. However, like all other programming languages the programming structure
consists of:
o Defining functions
o Constructing lists
o Extracting parts of lists
o Using extracted values or variables to perform certain tasks that can be
mathematical as in FORTRAN
o Displaying what has been calculated in the program on an AutoCAD screen
o Varying some of the variables and possibly animating to see the effects
graphically
The first line of an AutoLISP program has the definition of the function required or the
name of the program.
It is written as follows:
(defun name(global variables / local variables))
This is equivalent to declaring variables at the beginning of a program. The name will be
used when loading or calling the program in AutoCAD.
Global variables are those that will be used with the function, for example when loading
a function NAME, always include the function global variables otherwise the following
error will be generated.
Incorrect number of arguments to a function.
If the function defined does not have any global variables then it is simply entered without
any. Local variables are optional and are not included when loading a function. These are
variables used within a program but do not have to be entered by the user of the program.
Notice that global variables are declared before the / sign and local variables after the / sign.
This will become clear when we look at examples.
The next step is to assign values to variables. This can be done interactively or the user can
define these within the program.
(setq VARIABLENAME(getdist "Enter the distance:"))
Or (setq VARIABLENAME(getpoint "Enter the point:"))
The AutoLISP command getdist asks the user to interactively enter a value to be
assigned to the VARIABLE NAME. (This can be decimal or whole.)
The command getpoint asks the user to enter a point and this should be entered in the
form (x,y) or (x,y,z) on the command line. This can also be entered by the mouse by
clicking the LMB(left mouse button).
Defining points on the Screen.
The polar function is the common way used for defining points. The format is as
follows:
2
AutoLISP Programming AutoCAD® Release 2000 Course
For example:
To construct a line between two points A and B 60 units apart and point B at an angle of
50° to the horizontal from A.
Point B
60
500
Point A
Assuming point A is defined say by using the mouse or by simply entering the
coordinates, point B is obtained by using the following AutoLISP expression,
(setq ptB (polar ptA (/(* 50 pi) 180) 60))
The expression (/(* 50 pi) 180) is the angle 50° converted to radians because degrees
are not used in AutoLISP expressions.
The last thing that we need to do, having defined the corner points is to join up the
points and display them in AutoCAD.
Notice that 2 inverted commas are used at the end. This is to show that the line ends at
B. Normally when you use the command "line" in AutoCAD the line drawn will be
continues unless you terminate it by Ctrl-C.
Other commands such as zoom are used to give a maximum view of the object. In most
cases the displayed figure may overlap the AutoCAD Display Screen. In this case you
can either use:
(command "zoom" "e") i.e. displays the extents of the
object.
Or (command "zoom" "0.5") i.e. displays half the scale of the object.
3
AutoLISP Programming AutoCAD® Release 2000 Course
All the points that we discussed earlier will now be illustrated by a simple example of
drawing a rectangle where the user simply specifies the length and width and also the
position of one of the corner points.
A number of Editors are available on the computers for creating AutoLISP programs.
After switching on the computer it normally goes straight to the DOS prompt C:\> At
this prompt type:
C:\>edit rectan.lsp
and enter. It takes you straight to the editor and then type in your program. To save the
program you can either use the mouse or press the Alt key and Enter. Under FILES
there are various options and you can choose Save As and type in the name you want
with extension LSP for example c:\rectan.lsp. This will save your work on drive C.
After the program has been saved press the Alt key again and Enter, then choose Exit
Back on the DOS prompt C:\> go into AutoCAD.
Start a New Drawing and give it a name. The AutoCAD Display Screen has a
command line at the bottom. At this command line type:
Command: (load "c:rectan")
and your program will be loaded into the AutoCAD memory. This is shown-by the word
RECTANG (the defined function) appearing after the load command. If your program is
malformed or has errors these will be shown at this stage and you have to quit and go
back to the editor to start all over.
To run the function RECTANG that has been loaded in AutoCAD, on the command
line type:
Command: (RECTANG length width)
Notice that the function RECTANG is loaded with the values for length and width
because these are global variables. If these are declared as local variables then simply
RECTANG.
The rectangle will thus be drawn automatically. If however one decides to let the user
enter in the variables length and width, then these are declared as local variables and
questions can be used to ask the user to enter in the length and width.
8. )
For this case, the variables len and wid representing the length and width respectively
are global variables and hence are included when loading the function RECTANG.
Command: (RECTANG)
In both cases the rectangles are drawn automatically. This is just a simple example of
parametrics. AutoLISP programming is thus useful for drawing out such figures and
will be even more useful when it comes to complicated components that have variations
in certain dimensions.
Line numbers 1-10 have only been used for reference purposes otherwise they are not
part of the AutoLISP program.
1. Defining a point
A point is a list of numbers consisting of the co-ordinates of that point. For example in
the previous example the first corner of the rectangle is defined by the (x,y) or (x,y,z)
co-ordinate. The other subsequent points can be defined using the polar command
referring back to the first point.
2. Adding vectors
5
AutoLISP Programming AutoCAD® Release 2000 Course
7.4 Simulation
Designed models such as mechanisms can be simulated in AutoCAD. This is achieved by
programming loops and the use of conditional statements in AutoLISP.
Animation.
'One picture is worth a thousand words' summarizes a picture's ability to transmit huge
amounts of information rapidly. In many applications, a picture is the best way to present
information.
Inexpensive display hardware has opened the world of computer graphics to fields where its
use was not feasible or even considered a few years ago. Animation is the process of
creating dynamic display images with elements that appear to have motion. Animated
computer graphics are used in simulating real life scenes in flights, or films. Sometimes in
designing, it is useful to animate the resultant mechanisms of objects.
In linkage mechanisms, one link may initially be displayed at a certain position. Either the
angle of one of the links is then varied or the lengths are increased. The old display is
erased and the new one drawn. This effect may not be well pronounced on computers that
have low frequencies. With a higher frequency, the effect is more pronounced.
6
AutoLISP Programming AutoCAD® Release 2000 Course
1. IF Statement
IF (this is true) THEN do this
ELSE do this.
Example:
Consider the user putting in two variables a and b such that x is obtained from these
two variables by two formulae: i.e. x can either be (i) or (ii)
x =b + 4a (i) if b is zero or negative
x =b - 4a (ii) otherwise
Assuming for example that x is defined by (i) if b is zero or negative, otherwise x is
defined by (ii).
The sequence or syntax to solve this in AutoLISP would be:
SYNTAX MEANING
(setq a (getvalue "Enter a") obtain value for a
b (getvalue "Enter b") obtain value for b
)
(if (<^b 0) )setq x (+ b ( (* 4 a))) if b is less than or equal to 0 then
x=b+4a
(setq x (- b (* 4 a))) otherwise x=b-4a
)
SYNTAX MEANING
(setq a (getvalue "Enter a") Obtain or enter value for a
b (getvalue "Enter b") Enter value for b
)
(if (or ( - b 0)(<b 0)) (setq x (+ b if b=0 or b<0 then x=b+4a
(* 4 a)))
(setq x (- b (* 4 a))) otherwise x=b-4a
)
These two blocks are the same except that the first one is more efficient as it combines <
and =. There are instances where you however need to use OR.
2. COND Statement
Another commonly used conditional statement is the COND and is useful for testing the
validity of the user's input. Example:
Consider that the user has to put in 3 variables a, b, and c and that these have to satisfy a
7
AutoLISP Programming AutoCAD® Release 2000 Course
certain condition for the program to work otherwise it would not work e.g.
a< b<c when the values are entered a must be less than b less than c
You can write functions within functions and all are controlled by the brackets. The syntax
to test whether the user's input satisfies the above range is as follows:
SYNTAX MEANING
(defun getinput (/ a b c) Defining a function called
getinput
setq a (getdist "Enter a") Enter value of a
b (getdist "Enter b") Enter value of b
c (getdist "Enter c") Enter value of c
)
)
(get input) Call the function and input a, b
and c
(cond (OR (< b a) (> b c )) if b is less than a and also greater
than c
(prompt "ERROR: Ensure that a then prompt error
< b < c, Re-enter a, b and c")
(getinput) and then reenter the values
)
(T (prompt "The 3 values are If the condition a<b<c is met
acceptable")) then prompt that they are
acceptable
)
In this example you would have created a function 'getinput' within the main function
of the program and that function 'getinput" is used before the program is complete. This
is to ensure that the user enters the proper values before the whole program is executed.
The T stands for the true statement of the COND.
3. WHILE Statement
The most widely used conditional function for loops in AutoLISP is the WHILE statement.
Example:
Assume that you want to vary the angle of a linkage from θ = 0.0 radians to θ = pi radians in
steps of 1 radian
pi
8
AutoLISP Programming AutoCAD® Release 2000 Course
The syntax for the above linkage changing its position from 0 to pi radians in steps of 1 is as
follows:
SYNTAX MEANING
(setq theta 0.0) Setting the value of θ to 0.0 start point
(while (or (>= theta 0.0)(<= theta pi)) While θ is greater than pi equal to zero or
less than or equal to pi proceed and
Your program here. execute the program
(setq theta (+1 theta)) When you have finished executing or
calculating the main points increment
θ by 1 radian and go back to the WHILE
statement
)
The result is that initially θ is set to 0.0 and you can execute your program and then when
the program comes to the statement for increasing θ it goes back to the while statement and
the program is executed with the new value for θ. The program repeats until θ is pi radians
and then it stops.
Remember that for this to work, the closing bracket for the WHILE statement must be
inserted after θ is incremented. This is the principle behind animation.
7.6.1 Parametrics
There are various components in engineering made using the same processes or
procedures but the end products are available in difference sizes. Examples to illustrate
this would be similar to the ones covered in the previous chapter on blocks e.g. bolts,
screws and nuts. Bolts are available in different sizes but in most cases they are
produced using the same basic procedures, such that one is exactly similar to another.
They are usually specified as (M d x l). The d indicates the diameter of the bolt and the
l represents the length of the threaded part or shank, depending on whether it's a bolt or
a screw. One set of bolts may differ from another set depending on the length of the
unthreaded portion of the bolt.
9
AutoLISP Programming AutoCAD® Release 2000 Course
Fig : M d x l bolt
In manufacturing or ordering these kind of engineering components, the fundamental
figures to specify are d and l. The rest of the other dimensions of the bolt are related to
these 2. For example:
D = 2d, , a = 0.8l for a certain class of bolts, etc,
Currently, to draw a bolt in AutoCAD, involves going through the whole process of
drawing lines, circles and arcs, etc., and then trimming to end up with the required
drawing. In the event of a need for a different size of bolt or to place the same size of
bolt on the drawing on a cliff rent location, the whole process is repeated.
This can be time consuming and therefore costly. One way to solve this in AutoCAD is
to use blocks.
Another way is with the aid of AutoLISP. A small program can be written and once this is
loaded in AutoCAD, the user only specifies the diameter and length. Everything else will
be calculated and the required drawing made automatically. The following is a simple
AutoLISP program to perform this kind of task.
;PROGRAM BOLTS.
; AutoLISP Program to Output the required drawing of an
; M d x l bolt or screw.
; Adopted from W.R. Nyemba
; February 2008
(defun bolt(/ dia leng dep) (setq dia (getreal "Enter diameter of Bolt:")
Ieng (getreal "Enter length of Bolt:")
dep (getreal "'Enter depth of thread :")
)
(setq ans (getstring "Bolt or Screw?
(B/S?)"))
(if (or (= ans "b")(= ans "B"))(setq a (* 0.8 Ieng) D
(* 2 dia)) (setq a leng D (* 2 dia))
10
AutoLISP Programming AutoCAD® Release 2000 Course
)
(setq b (- Ieng a)
pt1 '(0.0)
pt2 (polar pt1 0.0 a)
pt3 (polar pt1 0.0 leng)
pt4 (polar pt3 (/(* 3 pi) 2) (/ D 3))
pt5 (polar pt4 0.0 (*0.8,dia))
len (sqrt(+ (* 0.2 dia 0.2 dia) (* (/ D 6) (/ D 6))))
pt6 (polar pt5 (atan(/ (/ D 6) (* 0.2 dia))) len)
pt7 (polar pt5 (/ pi 2) (/ D 3))
pt8 (polar pt6 (/ pi 2) (/ D 3))
pt9 (polar pt7 (/ pi 2) (/ D 3))
pt9a (polar pt8 (/ pi 2) (/ D 3))
pt10(polarpt9(/pi2)(/D3))
pt11 (polar pt10 pi (* 0.8 dia))
pt12 (polar pt11 (/(* 3 pi) 2) (/ D 3))
pt13 (polar pt12 (/(* 3 pi) 2) (/ D 3))
pt14 (polar pt 12 pi b)
pt15 (polar pt14 (/(* 3 pi) 2) dep)
pt16(polar pt2(/pi2)dep)
pt17 (polar pt14 pi a)
pt18 (polar pt15 pi (+ a dep))
pt19 (polar pt16 pi (+ a dep))
pt20 (polar pt8 pi (+ dia leng (* 1.5 dep)))
)
(command "line" pt1 pt2 pt3 pt4 pt5 "")
(command "line" pt1 pt17 pt14 pt12 pt11 pt10 pt11 pt12 pr9 pt12 pt13 pt7"")
(command "line" pt1 pt19 pt16 pt2 pt16 pt15 pt14 pt15 pt18 pt17 "")
(command "line" pt6 pt8 pt9a "")
(command "arc" pt18 pt20 pt19)
(command "arc" pt5 pt6 pt7)
(command "arc" pt7 pt8 pt9)
(command "arc" pt9 pt9a pt10)
The program also prompts to the user to specify whether it's a bolt or a screw that is
required. If it is a screw, the whole shank length / will be threaded and also the head will
be round and possibly with a hexagon cavity for Allen keys.
With this kind of program, every time a new size of bolt is required, the user simply types
in::
Command: (bolt)
at the AutoCAD command prompt and after entering the required parameters the new bolt
will be drawn on the screen.
11
AutoLISP Programming AutoCAD® Release 2000 Course
The use of AutoLISP enables the mathematical modeling of the behaviour of engineering
systems or mechanisms.
7.7.1 Autosurf
This package was written specially for complex surfaces to obtain appealing designs.
Products manufactured with complex sculptured shapes and curves, have proved to sell
better. Autosurf enables the design, visualisation and verification of these shapes.
7.7.2 Autovision
Autovision is used to turn any 3-D model into a high impact rendered image, making it
suitable as a conceptual mode! and in product presentations. Designs can be verified for
accuracy earlier in the design process and then communicated more effectively to clients,
colleagues and review boards.
Plan Vi e w of an M d nut.
2. Compile and simulate the program below for the rotation of a link with a circle at one
end about a central point.
; Simulation of a circle connected to an arm, W. R. Nyemba, 30/06/96
12
AutoLISP Programming AutoCAD® Release 2000 Course
13