Auto LISP Programing Guide
Auto LISP Programing Guide
Auto LISP Programing Guide
This tutorial is aimed at the AutoCAD users who would like to start learning AutoLisp. I suggest that you go through this tutorial along with
the AutoCAD Programmers Reference Guide. You can then lookup the relevant AutoLisp commands for a more detailed explanation. Hope
this helps you and Good Luck in your Lisping - Kenny Ramage
Principles of Programming
All AutoLisp programs must contain the suffix ".LSP" otherwise AutoCAD will not access them when loading. (eg. CHTEXT.LSP).
Use a simple text processor such as Notepad to create and edit your lisp files.
Charting
Draw out or write out in English what you want your program to do.
Variables
These are like empty boxes in which to store data, to be used later. In AutoLisp, variables may be a collection of letters or numbers as long
as they begin with the letters.
Example of legal variables are as follows:
ARC1
POINT1
PNT1
D3
An AutoLisp variable may contain more than one value in a single variable. A value can be anything, such as :
Real number
String
Integer
Pickset
Structuring
Structure your program in such a way that it is easy to understand, by yourself and everyone else. e.g. Keep input statements together.
Keep your arguments together. Keep your commands together. Track your work with the semicolon. When you begin a line with a
semicolon, anything you write after will be ignored by AutoLisp. It is used for documentation and explanation of your program. Write notes
about your program, what you are doing and what the variables are. A semicolon does not have to begin the line.
(prompt"Thislinewillprint");Thisisacomment
From where the semicolon begins, the remainder of the line is a comment statement.
Parentheses ( )
Parentheses are vital to writing AutoLisp programs. All commands are surrounded by parentheses. AutoLisp uses parentheses to nest,
allowing you to write a command that acts on (evaluates) another command. In turn, that command can act on another. As you add
parentheses, you're nesting commands become deeper and deeper. Remember to come out of the nest with an equal number of
parentheses.
Note: Always close what you open.
1.
(defundrawline()
The first way, you are saying that all variables you plan to use in the program are GLOBAL, which are variables that do not lose
their value after the program ends.
2.
(defundrawline(/pntlpnt2)
The second way, you are saying that the variables you are using are LOCAL variables, which are variables that have value only
for that program and while that program is running.
3.
(defunC:drawline()
The third way, as the first BUT the C: tells AutoCAD to treat that function as any other AutoCAD command.
4.
(defunC:drawline(/pntlpnt2)
The fourth way, as the second, but an AutoCAD command.
5.
(defundrawline(a/pntlpnt2)
The last, variable a receives the first value to it from outside the program.
Data Types
Integers
Are numbers ranging between -32768 and +32767 without decimal points eg: 1
Reals
Are numbers with a decimal point eg: 1.0
Strings
Strings are bits of text and can be up to a maximum length of 100 characters eg: Point 1
Lists
A list is a variable that has more than one element. A point in your drawing is described by the value of the X co-ordinate and the value of
the Y co-ordinate. In AutoLisp, that point can be described by a single variable, a list of two elements, the first being the X value and the
second being the Y value eg: ( 7 10 ). The following are also examples of lists: ( 5 9 7 2 ) and ( 1.5 2.3 4.9 ).
Atoms
If a variable has a single indivisible value it is an atom. For example, each element in the lists above is an atom e.g. 6 or A
The type function will return the data type of a variable. For example:
(type"Myname")
Will return STR meaning "string". In fact, you can try this for yourself now. Type the code above at the AutoCAD command prompt and hit
enter.
Input Commands
getpoint
getint
getreal
getcorne
Needs a second point on the screen and draws an elastic window from a previous point.
r
getstring
getdist
Needs a value either by picking on the screen or a number from the keyboard.
getangle
Needs an angle either by pointing on the screen or by typing an angle, which will be returned in radians.
getkword
getvar
initget
getorient
Is similar to the GETANGLE but is affected by the zero-degree base and the direction. It will always give you the absolute
angle using 0 degree base as EAST.
1.
(getpoint"\nPickaPOINTonthescreen:") Pick a point when prompted and AutoCAD will return the value (X Y Z)
of that point.
Tip: \n is a special escaped character that takes you to the next line (like a carriage return). The forward slash character tells
AutoLisp to interpret the following character as a special character rather than just as a letter "n". The "n" must be always be lower
case. The use of "\n" is purely cosmetic (it doesn't change the way the program works) but it does make everything much easier to
read for the user by starting each prompt on a new line.
Caution: Your prompt must always be between quotes, "prompt" otherwise you will get an error.
2.
(getint"\nEnteryourage:") Type an integer (such as 34) and AutoLisp will return that number.
3.
(getreal"\nEnteranumber:") Type a real number (such as 10.51) and AutoLisp will return that number.
4.
(getcornerpnt1"\nPicksecondpoint:") Will create an elastic window from the variable called "pnt1", which must
already be defined.
5.
(getstring"\nWhatisthedaytoday?:") Type some text and Autolisp will return that text.
Or
(getstringT"\nWhatisyourfullname?:") This prompt allows you to enter a string of words separated by
spaces. Ordinarily, AutoCAD will interpret a space in the same way it interprets a carriage return. The T is a special AutoLisp
symbol that means "true" it is used to allow spaces in string input. In fact, you can use any positive integer (such as 1) in place of
T but the T symbol helps to make the code more understandable.
6.
(getdist"\nHowlongistheline?:") Pick two points or type a length and AutoLisp will return that length.
7.
(getangle"\nWhatistheangle?:") Pick two points for the angle or type an angle and AutoLisp will return that angle
in radians.
8.
(initget1"YesNO")
(getkword"\nAreyougoing?(YesorNO):") Initget will control the next getxxx function and is used to specify a list of
valid options or keywords, getkword will accept only one of the words specifies using initget. In this case, the options are "Yes" or
"No". The 1 is an initget bitcode and it means that a null response is not allowed. See the section below for more details.
Tip: Just as in native AutoCAD commands, any valid option keyword can be entered simply by typing the upper case part of the
keyword. So, in the example above, to answer Yes to the prompt, you need only type "y" but to answer NO, you must type "no". This
is used to avoid potential ambiguities when 2 or more options begin with the same letter.
9.
(getvar"FILLETRAD") Would return the set value of the FILLETRAD system variable (fillet radius) eg : 0. 5
10. (getorient"\nWhatistheangle?:") Pick two points for the angle or type an angle and AutoLisp will return an angle
in radians relative to 0 degrees at East.
16
32
Example:
(initget(+124))
(getint"\nHowoldareyou?:")
Will only accept a positive, non-zero Integer eg: 21
Setq Command
Print Commands
Prompt
(prompt"Maybeyouneedarest")
This command is used simply to print a message on the command line. A line feed (\n) is not included so two consecutive prompt
commands will print both messages on the same line and without any spaces between them. Therefore, any printing after the prompt must
be preceeded by the (terpri)function or \n.
Terpri
This is a line feed that causes the next printed text to appear on the next line. It generally follows the prompt command. eg:
(prompt"Hello,howareyou?")(terpri)
or
(prompt"\nHello,howareyou?")
Prin1
This function prints the expression on the screen and returns the expression. It can be any expression and need not only be a string. The
expression can also be written to a file and will appear in the file exactly as it would on the screen.
(prin1"Hello") would print "Hello".
(prin1a) would print the value of variable a.
(prin1af) would print the value of variable a to an open file named in variable f.
Princ
Is the same as prin1 except that the control characters ("") are not printed. Can also be used to print a blank line by using no statement
after princ.
(princ"Hello") would print Hello.
Print
Same as prin1 except that a new line is printed before the expression and a space is printed after the expression.
Setvar
This function sets an AutoCAD system variable to a given value and returns that value. The variable name must be in double quotes. eg:
(setvar"blipmode"0) returns 0 and will switch blipmode off. 1 would switch it on again.
Doing Arithmetic
AutoLisp provides a number of arithmetic functions and although the format of these functions is consistent with other AutoLisp functions
(function first, followed by values), it is not one we are familiar with from school. The important thing to remember is that the order of the
values is consistent with what we already know. In other words (/273) is the same as 27 divided by 3.
(+11) returns 2.
(21) returns 1.
(*22) returns 4.
(/21) returns 2.
(1+1) returns 2 (Incremented).
(12) returns 1 (Decremented).
Polar
This function returns the point at an angle (in radians) and distance from a given point.
(polarpnt1ang1dist1) where pnt1, ang1 and dist1 are 3 previously assigned variables.
Inters
Examines two lines and returns the point where they intersect even if they do not physically cross one another.
(interspnt1pnt2pnt3pnt4) where pnt1 and pnt2 are the end points of one line and pnt3 and pnt4 are the end points of another.
(command"pline""50,50""50,70""70,70""70,50""c")
Example Programs
Drawing things
This program draws a rectangle by pointing to two points
(defunc:retan(/plp2p3p4)
(setqpl(getpoint"\nfirstcornerofrectangle:"))
(setqp3(getcorner"\nsecondcornerofrectangle:"))
(setqp2(list(carpl)(cadrp3)))
(setqp4(list(carp3)(cadrpl)))
(command"line"plp2p3p4"c")
(princ)
)
Converting data
(dtr) converts degrees to radians
(defundtr(a)
(*pi(/a180)))
Things to strings
strcase(stringcase)
Changes a string of text from lower case to upper case, leaving upper case characters as they are. eg:
(strcase"Hello") returns "HELLO"
(strcasea) returns the alphabetic characters in variable a from lower case to upper case.
strcat(stringcat)
Returns two or more separate strings as one. eg:
(strcat"H""ello") returns "Hello"
(strcatab) returns two strings in variable a & b as one.
strlen(stringlength)
Returns the length, of the characters of a string. eg:
(strlen"hello") returns 5.
(strlena) returns the length of a string in variable a.
substr(substitutestring)
Returns a part of a string, from a specified position, ending either at the end or another specified position. eg:
(substr"Hello2) returns "ello".
(substr"Hello21) returns "e".
(substr"Hello"32) returns "ll"
List Manipulation
The apostrophe character, ' serves a special function in AutoLISP. For example, if a group of items is preceded by an apostrophe, it is
treated as a list. eg:
'(20105) is treated as a list.
Angle
Returns an angle between two points in radians. To use that angle in AutoCAD you have to convert it back to decimal degrees. eg: (setq
a(anglepnt1pnt2)) sets the angle between pnt1 and pnt2 to the variable a.
To use a:
(command"text"pnt1"40"at) The text command with a height of 40, rotation angle assigned to variable a and a text string to
variable t. But ais not the correct rotation angle because it is in radians.
Append
Takes any number of specified lists and joins them together as one list. eg:
(append'(1020)'(3040)) returns the list: (10 20 30 40).
(appendab) returns the list in variable a and the list in variable b as one.
Distance
Measures the distance from two known points. eg:
(setqdist1(distancepnt1pnt2)) returns the distance between pnt1 and pnt2 and assigns the distance to a variable
called dist1.
Length
Returns the number of elements in a list. eg:
(length'(abcd)) returns 4.
Member
Looks for a match and returns that and the rest of the list eg:
(member'c'(abcde)) returns (c d e).
Nth
Returns the nth element in a list, where n is the number of the element to return. (Zero is the first element). eg:
(nth3'(abcd)) returns d.
Assoc (associative)
Often used with the (subst) function; the (assoc) function lets you search for a specific element, then assign that element to a variable.
Lets assume variable b is the list ((10 5.5 2.7)(40 5)) and you are looking for a value 40. You want to pull out the entire element and assign
it to a variablec. eg:
(setqc(assoc40b))
This assigns the entire element containing the 40 in the list b to variable c. Now c is a list that looks like this: (40 5).
Subst (subsitute)
Allows you to substitute one aspect for another. When substituting ALWAYS substitute the new item for the old in the list. Now lets
substitute 20 for the 5 in the variable c.
(setqb1(subst'(4020)cb))
Now b1 is the new list.
'(4020) is the new element substituted for the old element (40 5) c, found in list b.
If you want to use a variable which represents the value
(setqbl(subst'(40h)cb)) looks like it should work, but it does not. The new element will look like this: (40 h).
(subst) cannot interpret variables. You need to construct a new variable containing the entire list element, then use the new variable in
the (subst)function.
Cons (construct)
Constructs a new list with the new element placed at the begining. Assume variable c contains the following list: (40 5). Also, assume
variable h contains the real number 20.0 then:
(setqd(cons(carc)h)) Remember, (carc) gives you 40. Therefore, (carc) is the new first element, followed by the value
of h. Thus it produces a new list d (40 20.0).
Now we substitute:
(setqb1(substdcb)) That substitutes the new element found in variable d for the old element found in variable c. (In the list
found in variable b) and assigns the new list to b1.
Conversions
Angtos (angle to string)
Takes an angle in radians and converts it into a string, using a specific format. Angtos has two arguments, the first controls the format and
the second controls the precision.
Degrees
Degrees/minutes/seconds
Grads
Radians
Surveyor's units
(angtosa04) returns "180.0000" where 0 is the format (degrees) and 4 is the precision, in this case, 4 decimal places.
(angtosa00) returns "180"
(angtosa14) returns "180d0"0""
Fix
This function returns the convertion of a real number to an integer and drops the remainder. eg:
(fix8) returns 8
(fix8.6) returns 8
Float
This function returns the convertion of an integer to a real number. (One can use either real or an integer.) eg:
(float8) returns 8.0000
(float8.6) returns 8.6000
Ascii
Returns the convertion of the first character of a string into its ASCII character code. (an integer) eg:
(ascii"a") returns 97
(ascii"A") returns 65, upper and lower case characters have different ascii character codes.
(ascii"BLUE") returns 66
(ascii"BALL") returns 66, only the first character is evaluated.
Chr
Returns the convertion of an Integer representing an ASCII character code into a single character string. eg:
(chr65) returns "A"
(chr66) returns "B"
Scientific
Decimal
The real number can be set according to mode and precision. eg:
(rtos7.214) returns "7.200OE+00"
(rtos7.222) returns "7.20"
Conditionals
In AutoLisp, the equals character (=) is not an assignment function. In other words, it is not used to assign a value to a variable as it is in
some other programming languages. AutoLisp uses the (setq) function to perform this task. In AutoLisp, the equals character is used to
test if items are equal, it does not make them equal. This is very useful if we are trying to test certain conditions. For example, we can begin
to construct tests with an outcome such as "if one thing is equal to another thing, do something". That's what conditionals are all about;
they allow your program to make decisions.
If
(if) is the standard if-then-else statement. In AutoLISP you may only match one if statement with a then statement. eg:
(if(=ab)(setqb5(setqb6))
If a is equal to b, then b will be assigned the value 5. If it is not, then b will be assigned the value 6.
Cond (conditional)
This function accepts any number of lists as arguments. It evaluates the first item in each list (in order supplied) until one of these items is a
value other than nil. eg: A user's response string is variable s.
(cond
((=s"Y")1)
((=s"y")1)
((=s"N")0)
((=s"n")0)
(tnil)
)
This function tests the response and returns 1 if it is "Y" or "y", and 0 if it is "N" or "n", and nil otherwise.
Repeat
Similar to a loop but repeat will only go through the commands as many times as is told. eg:
(setqa10)
(setqb100)
(repeat3
(setqa(+a10))
)
(setqb(+ba))
)
Returns 140.
While
Is another loop control command available in AutoLISP. A loop is necessary if you want to repeat a command. However, unless you have a
way of controlling it, the program will run forever and hang you up. eg:
(setqa"w") Sets up the controlling variable to a value other than nil.
(whilea The loop will continue, begining with the commands that follow, until the variable a is set to nil.
(somefunctions) Are the functions that are performed in the loop.
(if(=cd)(setqanil)) Evaluates if c is equal to d, and if so, sets the loop controlling variable a to nil to end the loop.
) A closing parenthesis closes the loop, and program will continue with the commands after this.
Entities
An entity is the smallest object you can place on your screen. The following are entities: LINE, CIRCLE, ARC, TEXT, POLYLINES, etc.
Entities are stored and referenced in the drawing database. They can be changed and manipulated using AutoLISP to suit your needs.
Each entity has a massive definition in AutoCAD's database. eg: The data for a single line contains the following info:
Entity name, Entity type, Layer, Color, Beginning X Y coordinate, Ending X Y coordinate, Line type, etc. You can modify any of the above
aspects. An example of an entity list:
(1<Entityname:60000014)(0"CIRCLE")(8."LAYER1")
(10.50.000100.000)(40.60.000)
It is an entity list of a circle on layer LAYER1, center point relative to 0,0 of 50.0,100.0 , and a radius of 60.0
(setqa(ssget)) will prompt you to select objects. You have now created a selection set with a specific name, <Selection set:l>
,assigned to variablea, or use filter option (setqa(ssget"X"'((0."TEXT")))) to search database for certain entities or codes.
Sslength
Gives you the length or number of selections made.
More Examples
Change Cross Hair Angle
This program permits you to draw lines perpendicular to other lines. The program measures the angle of the line chosen, and shifts the
SNAP ANGLE to the angle of that line. Use ORTHO ON and draw perpendicular to your chosen line.
(defunc:perpdon(/abpntlpnt2angl)(graphscr)
(setqa(entsel))
(setqb(entget(cara)))
(setqpntl(cdr(assoc10b)))
(setqpnt2(cdr(assoc11b)))
(setqangl(anglepntlpnt2))
(setvar"snapang"ang1)
(princ)
)
(defunc:perpdoff(setvar"snapang"0)
(princ)
)
Erase Screen
Erases everything on the drawing screen. If you are in a ZOOM ALL position, the program erases everything within the limits of the
drawing.
Note: if you accidentally invoke this command, you can recover with OOPS.
(defunc:erasescr(/lu)
(setql(getvar"limmin"))
(setqu(getvar"limmax"))
(command"erase""w"lu"")
(princ)
)
Change Layer
Lets you select objects by any selection method and change their layer. The target layer is chosen by simply pointing to an object on the
desired layer. All objects selected will then change to that target layer. To test this program, you will need to create a drawing with objects
on different layers.
(defunc:chlayer(/a1a2nindexb1b2d1d2b3)
(graphscr)
(prompt"\nselectentitiestobechanged:")
(setqa1(ssget))
(prompt"\npointtoentityontargetlayer:")
(setqa2(entsel))
(setqn(sslengtha1))
(setqindex0)
(setqb2(entget(cara2)))
(setqd2(assoc8b2))
(repeatn
(setqb1(entget(ssnamea1index)))
(setqd1(assoc8b1))
(setqb3(substd2d1b1))
(entmodb3)
(setqindex(+index1))
)
(princ)
)
Now let's examine the program line by line.
(defunc:chlayer(/a1a2nindexb1b2d1d2b3)
Defines the function with all local variables.
(graphscr)
Changes to graphics screen.
(prompt"\nSelectentitiestobechanged:")
This is a prompt statement.
(setqa1(ssget))
Allows you to select the objects to be changed. The selection set is assigned to variable al.
(prompt"\npointtoentityontargetlayer:")
This is a prompt statement.
(setqa2(entsel))
This is a special type of selection statement that allows you to select only one entity.
(setqn(sslengtha1))
Measures the number of entities in the selection set in variable a1.
(setqindex0)
Sets the variable called index to 0.
(setqb2(entget(cara2)))
This statement gets the entity list from a2. Thus, a2 is assigned the entity list.
(setqd2(assoc8b2))
This looks for the code 8 in entity list a2, then assigns the sublist to d2.
(repeatn
This begins the loop that pages through the selection set.
(setqbl(entget(ssnamea1index)))
This gets the entity list and assigns it to b1.
(setqd1(assoc8b1))
Substitute text
This program lets you choose a line of text and substitute another line at exactly the same place.
(defunc:subtext(/abded1b1y)
(prompt"\nSelecttextline:")
(setqa(entsel))
(setqb(entget(cara)))
(setqd(assoc1b))
(prompt(cdrd))(terpri)
(setqe(getstring1))
(setqd1(cons(card)e))
(setqb1(substd1db))
(entmodb1)
(setqy(getstring"\nIsthiscorrectY:"))
(if(=(srtcasey)"N")(entmodb))
(princ)
)
(command"text"pla"0"e)
(setqpl(list(carp1)((cadrp1)c)))
(setqf(getstring))
(if(=f"*")(setqdnil))
)
(princ)
)