0% found this document useful (0 votes)
15 views

Auto LISP

Notes

Uploaded by

ashrafmulla767
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Auto LISP

Notes

Uploaded by

ashrafmulla767
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

My Notes

CP205-2

AutoLISP/Visual LISP® is a powerful way to extend AutoCAD® functionality, but many avoid
using itbecause they think it’s too hard to learn. This course starts at the beginning and
rapidly moves
youthroughconceptssuchaslists,accessingthecommandline,storingandretrievingvariables,wri
tingyourown command functions, working with simple sets, and controlling AutoCAD’s start-
up to achieve greaterstandardization of your AutoCAD environment. If you want to tap the
power of AutoLISP, fasten yourAutoCADbeltforthis session.

AbouttheSpeaker:

Robert is head of the Robert Green Consulting Group and a 13-year veteran speaker at
AutodeskUniversity. You've likely read his work in CADalyst magazine, where he authors the
"CAD Manager"column,orinhisbi-monthlyCADManager’s
Newsletter.HeholdsadegreeinMechanicalEngineeringfrom the Georgia Institute of
Technology and gained his CAD skills from 21 years of AutoCAD®,MicroStation®, and
MCAD® software usage. Since starting his own company in 1991, Robert
hasperformedconsultingandteachingduties forprivateclientsthroughouttheU.S.andCanada.

Website/email:www.CAD-Manager.com
TheAutoLISP®CrashCourse

2
TheAutoLISP®CrashCourse

Originsandexpectations
AutoLISP is a descendant of Common Lisp, which is actually a very old programming
language
thatwasconceptualizedforartificialintelligenceapplications.Italsohappenedtobeopensourcea
ndwasthereforeanideal(andcost-free) wayforAutoCADtobe
extendedwithaprogramminglanguage.
Since AutoLISP doesn’t have to be compiled, meaning you can run programs directly, it
was even moreideal as almost nobody but hard-core coders even knew what a program
compiler was in the mid-1980’s.
AutoLISP is a very powerful language that can take years to learn and master.I’ve been
working with itsince 1990 and I still learn new things about AutoLISP on every
project.Having said this, I’d like to saythat there is a lot you can do with AutoLISP without
having to be a programming jock if you approachthingswith acookbook-style approachand
use existing routines.

Keyfiles,functionsandvariables

The first thing to understand is that AutoLISP has some key files and a key function that
perform startupoperations for you.The key files can contain custom AutoLISP code that you
want loaded wheneverAutoCAD starts up.There are also a few useful functions that
AutoLISP has predefined to performstartupoperations for you. I’llsummarizeeverything
here:

ACAD200?.LSP NameslikeACAD2005.LSP,ACAD2006.LSP,ACAD2006.LSP,
ACAD2008.LSP,etc.ThisfileloadsfirstwhenAutoCADstartsup.
ACAD.LSP ThisfileloadssecondwhenAutoCADstartsup.
ACAD200?DOC.LSP NameslikeACAD2005DOC.LSP,ACAD2006DOC.LSP,
ACAD2007DOC.LSP,ACAD2008DOC.LSP, ACAD2009DOC.LSP,etc.
ThisfileloadsthirdwhenAutoCADstartsup.
ACADDOC.LSP ThisfileloadsfourthwhenAutoCADstartsup.
MENUNAME.MNL This file loads after the previous files but only when its menu
counterpart(either an MNUor MNCfile) isloadedinto
AutoCAD.ByplacingAutoLISP code in this file you can be assured
that the code will be loadedinto memory ONLY when the parent
menu is in use.Note that the code isonly loaded once (like the
ACAD.LSP) rather than with each
drawingsession(liketheACADDOC.LSP file).Plan accordingly.
ACADLSPASDOC ThisvariablecontrolstheloadingofACAD.LSP.ACAD.LSP fileonly
loadsonce,whenAutoCADfirststarts,unlessyousetthevariable
ACADLSPASDOCto1ratherthanthedefaultsettingof0.

3
TheAutoLISP®CrashCourse

EXERCISE:KeyFiles,Functionsand Variables

ToverifythatyoucancreateanAutoLISPfilethatloadsandexecutes,followthesesteps:
 Openatext editorlikeNotepad

 Type in the following line in the Notepad session taking great care to match all the
parenthesesandquotesas I have

(prompt“TheACADDOC.LSPfilehasloaded.”)

 Now save the file with the name ACADDOC.LSP and place the file in the SUPPORT
folder ofyour AutoCAD application software.Typical locations would be as follows
depending on yourAutoCAD version:

C:\Program Files\AutoCAD 2006\


SupportC:\Program Files\AutoCAD 2007\
SupportC:\ProgramFiles\AutoCAD2008\
Support

 Start AutoCAD and check your command prompt history (use the F2 key) to
be sure themessage“The ACADDOC.LSP filehasloaded”shows up.

 StartmultipledrawingsessionsinthesamesessionofAutoCADandverifythatthesa
memessageisdisplayedatthecommand prompthistory aseach drawingstarts.

Recommendation

The above methodology is recommended for adding basic AutoLISP syntax to your
AutoCADenvironment.By using the ACADDOC.LSP methodology you don’t have to worry
about
theACADLSPASDOCsettingandsincethefileprobablydoesn’texistinyourinstallationalready,t
here’sessentiallyzero chanceyou’llwrite overordestroy any existingcustomization.

Note1:UsingACADDOC.LSPintheSUPPORTdirectoryyieldsmaximumresults,lowcomplexityandfarlessch
ance of messing something up.
Note 2:Be sure to use a plain text editor like Notepad rather than a word processing program
likeWord.Notepadwillstripoutweirdcharacterslikebackwardquotemarks thatcancauseyourprogramto
malfunction.

4
TheAutoLISP®CrashCourse

Syntaxbasics

So now that you know which files to put your AutoLISP code in, let’s establish the basics
of AutoLISPsyntaxso youcan startwriting some code.Thebasic topics youneed
tounderstandare:
 Listsandarguments
 RulesofAutoLISP
 Variables
 Functions
 Accessingthecommandline
 Specialcharacters
 Userinput

We’ll examine these topics using a combination of lecture and viewing code
examples.Pleaseunderstand that given our time constraints I can’t fully develop all the
theory behind these commands.I’ll have to ask you to trust me for the meantime, then
research the language more thoroughly laterwhenyou have a workingknowledge of the
language.Let’s get started!

Listsandarguments

Anything you do in AutoLISP is formatted as a list.Lists can have both ARGUMENTS


andFUNCTIONSembeddedwithinthemsoyoucanperformvariousactivities.Hereareafewexa
mples:
(+20 30) Here + is the FUNCTION and the two
numbers areARGUMENTS
(command“line”“0,0”“1,1”“”) Here COMMAND is the function, all
others areARGUMENTS
Ifyoustudymoreyou’llstarttoseethatanyAutoCADentitycanbedescribedasacomplexlistliket
his:

((-1.<Entityname:400b1580>)(0."LINE")(330.<Entity name:40094cf8>)(5."378")(100.
"AcDbEntity")(67.0)(410."Model")(8. "2")(100."AcDbLine")(10198.44178.7860.0)(11 247.87
179.5890.0)(2100.00.01.0))

Thoughitisn’tobvious,thislistdescribesalinethatisdrawnonlayer“2”withastartpointandendp
ointand aUCSvector of0,0,1. Onceyou start toread lists,you’reon your way!
Lists are simply a way to group information or to submit information, in the form of
ARGUMENTS to aFUNCTION as we illustrated above.The AutoCAD entity lists allow you to
perform actions
onAutoCADentitiesviamoreadvancedprogrammingtechniquesthanwe’lllookattoday.Ijustwa
ntyoutohave a glimpse of what’s under AutoCAD’s hood.

5
TheAutoLISP®CrashCourse

RulesofAutoLISP

“Forevery(thereisanequalandopposite)”–Einsteincirca1939

6
TheAutoLISP®CrashCourse

Likethis: (setqA 3.0)


Notlike this: (setqA3.0)) or(setqA 3.0

Samegoesforquotemarks!
Likethis: (setqname“RobertGreen”)
Notlike this: (setqname“RobertGreen)or(setqnameRobertGreen”)

When formatting numbers always avoid “invalid


dotted pairs.”Likethis: (setq A 0.5)
Notlike this: (setqA.5)

Arithmeticfunctionsalittledifferentthanyou’reusedto.Forexample:
Standardlanguage AutoLISP equivalent Result

8+ 4 (+8 4) 12
8+ 2.3 (+8 2.3) 12.3
5.0÷4.0 (/5.0 4.0) S1.25
5÷4.0 (/5 4.0) 1.25
5.0÷4 (/5.0 4) 1.25
5÷4 (/5 4) 1 (Why?
Integers!)

More complex math gets a little persnickety.Look at the following examples and
remember thatAutoLISPworks fromthe inside outwith respecttoparentheses.
Forexample:

Standardlanguage AutoLISPequivalent Result


(8+ 4) *3 (*(+ 8 4)3) 36
(3.0*5.0)÷4.0 (/(* 3.05.0) 4.0) 3.75
((4 +4)*3) ÷2 (/(* (+ 44) 3) 2) 12

I’ll talk more about data types in an upcoming session but for now take careful note that
how you enternumbers(real orinteger) has everythingto do withhow thenumbers get
processed.

7
TheAutoLISP®CrashCourse

Accessingthecommandline

To make AutoCAD and AutoLISP shake hands, the most basic skill set you’ll need is
accessing thecommand line.I alluded to the idea of a COMMAND function with
arguments in the previous sectionbut I didn’t do any real practical examples.Let’s have
a look at several possible examples of “talking”toAutoCADvia the AutoLISP command
line interface.
If you wanted to draw a line between two user-supplied points on the screen, you’d do
the following:Typein LINE to start the line command
Click POINTforfirstpointlocation
Click POINTforsecondpointlocation
Typein ENTER tohaltthe command

InAutoLISPyou’ddo itthisway:
(command“line”pausepause“”)

Note:The PAUSE instruction waits for the user and the “” is equal to hitting the ENTER
key.Why?Because that’s the waythe good folks at Autodeskset it up!
Howaboutafewmore examplesofcommandlineaccessthatyoumaywanttoactuallyuse?
Hereareafew examples:

AutoLISPfunction Purpose _
(command“viewres”“y” “5000”) Setsviewresolutionfornojaggycircles
(command“-color”“BYLAYER”) Sets color to
BYLAYER(command“-linetype”“set”“BYLAYER”“”) Sets linetype to
BYLAYER(command“menu”“menuname.mnc”)

Loadsmenufileofyourchoosing

Nowlet’slookatanexamplewithuserinput:

AutoLISPfunction Purpose _
(command“viewres”“y” pause) Setsviewresolution toauservalue

8
TheAutoLISP®CrashCourse

Variables
While knowing about lists is one thing, doing something functional with lists depends on
being able tostoreand pass variableswithin lists.

Firstthingsfirst:Howdoyoustoreavariable?
Let’ssayyouwantedtostoreavariablecalledVALUEthat has the number 12.7 associated with
it.In order to set the variable we need to use the SETQfunction(think SET eQual) like this:

(setqVALUE12.7)

This particular variable would be a REAL NUMBER variable.Some other variable types are
shownherefor your reference:
(setqVALUE1) This would be an INTEGER
variable(setqVALUE“Happy”) This would be an STRING
variable(setqVALUE1) ThiswouldbeanINTEGERvariable

Nowwhen youinteractwithAutoCADyouhave
topassthevariableinthecommandline.Usethiscaseas anexample:
(setqVIEWRES_VALUE5000)
(command“viewres”“y”viewres_value)

Whatwouldhappeninthiscase?
(setqVIEWRES_VALUE“HappyBirthday!”)
(command“viewres”“y”viewres_value)

Thiswouldn’tmakemuchsense,wouldit?
Whenyouwriteaprogramyouhavetomakesurethatthevariables you use match up with the
AutoCAD commands the variables are “speaking” to.It makessense to pass a numeric
value to the VIEWRES command, but it doesn’t make any sense to send it astring-
typevariable.Understandingthissimpletrickofvariabletyping makesthingsaloteasier.

9
TheAutoLISP®CrashCourse

Userinput
Let’s say you wanted to write a program that would create a wheel with some spokes in
it.Well, howmany spokes should the wheel have?If you write a program with a known
number of spokes, say 8,the program could then draw wheels with 8 spokes.Wouldn’t it
be better to write a program that drawswheels with a variable number of spokes?For that
matter, how about writing a program where youspecifythenumber of spokes and
thediameter of the wheel?
In order to specify how many spokes are on the wheel and how big the diameter is,
you’ll need to asktheuser to define thosevariables like this:
(getdist“\nInputadistance:”) Prompts the user for a distance
value(getreal“\nInputarealnumber: ”)Promptstheuserfor
arealnumbervalue(getint“\nInputanintegernumber:”)

Promptstheuserforanintegervalue
(getstring“\nInputtext:”) Promptstheuserforastring/charactervalue

Nowlet’sassociatetheinputtheuser givesustoanamedvariablelike this:


(setq user_dist (getdist “\nInput a distance: ”))
(setquser_real(getreal“\nInputarealnumber:”))
(setq user_int (getint “\nInput an integer number: ”))
(setquser_string (getstring“\nInput text:”))

Or,torevisitourspoke/wheelanalogy,howaboutthis:
(setqwheel_dia(getdist“\nEnterwheeldiameter:”))
(setqspokes(getint“\nEnternumberofspokes:”))

Usercommandfunctions
OK, we know how to collect information from the user and we know how to pass that
input toAutoCAD’s command line. But how can we do all this in a way that adds to
AutoCAD’s native set ofcommands?After all, wouldn’t it be ideal if we could write
AutoLISP routines that would trick AutoCADinto thinking it had new commands?If we do a
good enough job, our CAD users won’t even knowwe’veprogrammed commands for
them.
Let’shaveafewsimpleexamples soyoucanseehow itworks:
Theidea: We want to create a ZA command that does a
zoom all.Thecode: (defun C:ZA ()
(command “.zoom” “a”)
(princ)

10
TheAutoLISP®CrashCourse
)

Here’swhattheroutineisdoingonaline-by-linebasis:

11
TheAutoLISP®CrashCourse

(defunC:ZA() ReservesacommandcalledZAwithnoinputstothecommand
which explains the () after the command name.Don’t
worry aboutwhy the () works as it does now; to get more
into this wouldrequiremuch more detailed coverage.
(command“.zoom”“a”) Engagesthecommand lineandpassesthearguments.ZOOM
and A for all to the command processor.Why the “.” in
front ofzoom, you ask?Because it guarantees that we’ll
use the nativeZOOM command instead of any other
version that may beredefined.More on this later.
(princ) Clears the print console and suppresses AutoLISP from
leaving aNIL result at the command line as the function
terminates.Don’tworry about why it works, it just does
and your program will look alotcleaner for using it.
) Closes the function out.This actually balances the
misbalancedparen count in the first line of the function.
(You did notice theimbalance,right?)

Herearea fewmore Iliketo use:

(defunC:VR()
(command“viewres”“y”“5000”)
)

(defunC:BL()
(command“-color”“BYLAYER”)(command
“-linetype” “set” “BYLAYER” “”)(princ)
)

12
TheAutoLISP®CrashCourse

Moreusercommandfunctions
Let’slookatsomeadditionalfunctionsandtrytofigureoutwhytheyworkandcrankupthecomplexi
tyjust a little to keep things interesting.I’ll comment on the code in comment form (that is,
the codeincludesa“;” characterwhichallows usto writecommentsin
ourprogramming).Heregoes:
Theidea: We want to create an FZ command that performs a fillet command
but makessurethat theradiusisset to 0.0so we filletsharpcorners.
(defunc:fz() ; DefineanFZcommand
(setvar“filletrad”0.0) ; Set the fillet radius to 0.0 using
SETVAR(command“.fillet”pausepause) ; Invoke FILLET and wait for two user
inputs(princ) ;Clear the command line
)

We learned that we can set AutoCAD variables using the SETVAR function very easily.It
turns out thatyou can set a variable using SETVAR and can read the value of any variable
using, cleverly enough,GETVAR.Don’t know which variable you need?Look in the AutoCAD
help file under the commandtopicSETVAR and you’ll finda list of all thevariables and what
theydo!
Theprogramwillworkbutitwouldbebetterifwecheckedthevalueofthefilletradiusfirstandthenm
adesurewe putit backtheway wefound itwhen ourprogramis donerunning.Here’s how:
(defunc:fz() ; Definean FZcommand
(setqold_filletrad(getvar“filletrad”)) ;Storetheoldfilletradiusvalue
(setvar“filletrad”0.0) ; Set the fillet radius to 0.0 using
SETVAR(command“.fillet”pausepause) ; Invoke FILLET and wait for user
inputs(setvar“filletrad”old_filletrad) ; Put thefillet radius back
(princ) ;Clearthecommandline
)
This example illustrates reading a system variable value into an AutoLISP variable,
then using thatvariable later in the program to AutoCAD’s fillet radius to its previous
value.That’s it!Not so bad,really.

AutoPurge (ATP)
Here’s a function I like to use daily.It does an autopurge and save (thus combining two
commands intoone)by keying in ATP:
(defunc:atp()
(command “-purge” “a”“*” “n” “.qsave”)
(princ)
)

13
TheAutoLISP®CrashCourse

Coolstufftoknow

ThereareafewotherlittlehandythingstosprinkleintoyourAutoLISPsessionsthatI’llcoverherean
dcommentonone by one:

Comment“;”Lines
You may have noted my use of the semi-colon character in some examples.The semi-
colon is thecomment character in AutoLISP which allows you to embed notes in the code.I
find commenting
veryhelpfulbecauseseveralmonthsfromnowwhenI’mworkingonaprogramIwon’trememberw
hat Iwasdoingway back when Iwrote the program.
Anythingthatcomesafterthesemi-colonissimplyignoreduntilthenextlineoftheprogramstarts.

Dash“-“FormCommands
WhydidIuse–PURGEinsteadofjust PURGEintheATPexample?
I used the dash form of the PURGE command specifically because I didn’t want the dialog
form of thecommand invoking.While the dialog form of commands like PURGE and LAYER
are cool for the user,anAutoLISPcommandcan’treachout andgrabthe mouseto
interactwiththe command,right?
Soifacommandhasadialogbox,likeLAYERfor example, justtryputtingadash“-“infrontof
thecommandand see if it works!
I prefer using the dash form of commands because I can always go to AutoCAD’s
command promptand type in the dash form of the command and see exactly how it will
behave.I therefore make fewermistakeswriting my programs!
Extra credit:If you’re a glutton for punishment look in the AutoLISP function reference (find it
underthe AutoCAD help system) and look up the INITDIA function.This AutoLISP function provides a
moredetailedexplanation of howdialogs are handledwithin AutoLISP functions.

Dot“.“FormCommands
In my FILLET programming example, why did I type the command as “.FILLET”
rather than just“FILLET”?
Iusedthedotformofthecommand
justincasesomeenterprisingCADmanagerhadundefinedtheFILLET command
previously.The dot form of the command allows you to call the command even
ifhasbeen undefined.We’ll talk moreabout undefining functionsshortly.

14
TheAutoLISP®CrashCourse

AlertingUsers
Youcansendamessagetotheuserlikethis:(alert“Messagegoeshere”)

Note:TheusermustacknowledgethealertbyclickingtheOKbutton!

Undefiningcommands
You can turn AutoCAD commands off
like this:(command “.undefine”
“LINE”)
(command“.undefine”“TORUS”)
This way, if you don’t want users messing with a command, you just shut it off.Place the
code in yourACAD.LSPfileandit’ll havetheequivalent effectofdisablingAutoCAD’scommand
vocabulary.

Undefiningandalerting
Youcanundefineacommandand alerttheuserlikethis:

(command “.undefine”
“TORUS”)(defunC:TORUS ()
(alert“Idon’twantyouusingthatcommand
!”)(princ)
)

RedefineviaAutoCAD
TobringacommandbacksimplyusetheREDEFINEcommandattheAutoCADcommandpromptli
kethis:
Command:redefine
Entercommandname:torus

RedefineviaAutoLISP
15
TheAutoLISP®CrashCourse
Nowtakeitanotherstepandredefinethefunctionwithanalerttothe userlikethis:

16
TheAutoLISP®CrashCourse

(command“.undefine”“TORUS”)

(defunC:TORUS()
(alert“Idon’twantyouusingthatcommand
!”)(princ)
)
Thiswaytheuserwillgetthemessage!

ControllingCommandEcho
Many times you may have a program that invokes a command, yet you don’t want the
user to see thecommand you’ve invoked.As an example, the BL function I wrote earlier
could be made to run inSTEALTH MODE bydoing this:
(defunC:BL()
(setvar“cmdecho”0) ; Turns the echo
off(command “-color” “BYLAYER”)
(command“-linetype”“set”“BYLAYER”“”)
(setvar“cmdecho”1) ;Turnstheechobackon
(princ)
)

17
TheAutoLISP®CrashCourse

MaterialsandPowerPoints
You can download the updated course guide (with any additional notes or
corrections) for thispresentationatmywebsitewww.CAD-Manager.comon
theAU2008 Resources page.
I will send you a PDF copy of the session PowerPoint presentation if you request it. Just
send an emailto me at [email protected] and be sure to put CP205 – AutoLISP
Crash Course in thesubjectlineso I’llknow which classyou attended.
I’llreplytoallinformationrequestsuponmyreturntoAtlantaonDecember6th.

AutoLISP®ReferenceMaterials
You can find a wide range of information on customization, programming and CAD
management at mywebsite:www.CAD-Manager.com

Downloads:I’ve found CAD Depot to be a very useful source for public domain AutoLISP
utilities youcanuse asinspirationfor your ownroutines. Youcan find theAutoLISP area at:
http://www.caddepot.com
Besides AutoLISP routines, there’s a lot of other nice material at CAD Depot worth
some of yourbrowsingtime.

AutoLISP help:Also be sure to check out the AutoCAD help resources under the
DEVELOPERGUIDEsectionforawealthofinformationonAutoLISPcommandsandfunctions.You
mayevenwantto try working the GARDEN PATH example tutorial now that you have a bit
of a grasp of how to dealwithAutoLISP.

18

You might also like