ABCs of Autolisp PDF
ABCs of Autolisp PDF
1
Copyright2001GeorgeOmura,,Worldrightsreserved
Introduction
OneofAutoCAD'sgreatestassetsisitsadaptability.Youcancontroljustabouteveryaspectof
AutoCAD'soperationsfromtheappearanceofitsdrawingeditortoitsvarietyofmenus.Akeyelement
ofthisadaptabilityisitsbuiltinprogramminglanguage,AutoLISP.WithAutoLISP,youcanvirtually
writeyourowncommandsorredefineothers.
YoucanthinkofAutoLISPasaverysophisticatedmacrobuildingfacility.(Simplemacrosarelike
scriptsthatautomaterepetitivekeystrokes.)Youdon'tneedtobeaprogrammertouseAutoLISP.In
fact,AutoLISPisdesignedsothateverydayusersofAutoCADcanstarttouseitafteraminimumof
training.ThisbookmakesAutoLISPaccessibletoAutoCADuserswhoarelookingforawayto
enhanceandextendtheiruseofAutoCAD.
TheABCsofAutoLISPbyGeorgeOmuraW
hoshouldreadthisbook
ThisbookintroducesnonprogrammerstotheuseofAutoLISP.Ifyouareanintermediatelevel
AutoCADuser,interestedinlearningaboutthispowerfultool,thenthisisthebookforyou.Ifyouare
justbeginningtolearnAutoCAD,thenyoushouldprobablybecomeabitmorefamiliarwithAutoCAD
beforeattemptingtolearnAutoLISP.Thisbookassumesthatyouhaveatleastanintermediatelevelof
expertisewithAutoCADandareacquaintedwithsimpleWindowsoperations.
H
owThisBookIsOrganized
Thebookisdividedinto11chapters.Thefirstthreechaptersgiveyouanintroductiontoprogramming
inAutoLISP.TheChapter1introducesyoutoAutoLISPbyshowingyouhowtouseitdirectlyfrom
theAutoCADcommandprompt.TheChapter2showsyouhowtocreateandsaveprogramsinafile.
Chapter3discusseswaysoforganizingyourprogrammingprojectsandhowtomanageyour
computers'memory.
ThenextfourchaptersshowyouhowtouseAutoLISPtodoavarietyofeditingtasks.Chapter4
discussesthefunctionsthatallowyoutoasktheuserforinput.Chapter5explainshowtobuild
decisionmakingcapabilitiesintoyourprograms.Chapter6showsyouhowtodealwithgeometric
problemsusingAutoCAD.Chapter7discussesthemanipulationoftext.
ThelastfourchaptersshowyouhowAutoCADandAutoLISPinteract.InChapter8,youwillseehow
youcancontrolmanyfacetsofAutoCADthroughAutoLISP.Chapter9delvesintolists,afundamental
componentofallAutoLISPprograms.Chapter10showsyouwaysofmodifyingAutoCADobjectsby
directlyaccessingtheAutoCADdrawingdatabase.Andfinally,Chapter11looksatwaystodigdeeper
intothedrawingdatabasetogetinformationoncomplexdrawingobjectslikepolylinesandblock
attributes.
Inaddition,fiveappendicesareincludedasreferencematerialtothebook.Intheoriginalversionofthis
book,theseappendicescontainedtheresourcesindicatedbytheirtitle.Inthiselectronicversion,these
appendicesofferdirectionsonhowtofindinformationintheAutoCADhelpsystem.Thefirstthree
showyouhowtofindinformationontheAutoCADmenustructure,AutoLISPerrormessages,and
AutoCADgroupcodes.Thefourthappendixdescribeshowtofindinformatononthestandard
AutoCADdimensionvariablesandsystemvariables.Thefifthappendixdescribeshowtofind
informatonontheTablegroupcodes.
2
Copyright2001GeorgeOmura,,Worldrightsreserved
TheABCsofAutoLISPbyGeorgeOmura
H
owtoUseThisBook
Eachchapteroffersexercisesandsampleprogramsthatdemonstratesomegeneralconceptregarding
AutoLISP.Throughtheseexercises,thebookshowsyouhowprogramsdevelopfromideasinto
finished,runningprograms.Also,theinformationyoulearninonechapterwillbuildonwhatyoulearned
inthepreviouschapter.Thisway,yourknowledgeofAutoLISPwillbeintegratedandcohesive,rather
thanfragmented.Forthisreason,thebestwaytousethisbookistoreadeachchapterinorderanddo
alloftheexercises.Sincethetopicsareorientedtowardaccomplishingtasksratherthansimplyfocusing
onindividualfunctions,youwillhaveagoodgraspofhowtouseAutoLISPinrealworldsituationsby
theendofthisbook.
W
heretoFindtheLISPPrograms
Asyoureadthechaptersanddotheexercise,youwillbeaskedtoenterprogramcodeintoafile.If
youareinahurry,youcancutandpastethecodedirectlyfromthechapteryouarereading.Thiswill
saveagooddealoftime,butmakesureyoustudythecodethatyoucutandpaste.
Thisbookwasoriginallypublishedin1990bySybexInc.Ithasbeenreproducedhereinanelectronicformatby
theAuthorforthebenefitofMasteringAutoCADreaderseverywhere.Enjoy....
Copyright2001GeorgeOmura,,Worldrightsreserved.Nopartofthispublicationmaybestoredinaretieval
system,transmitted,orreproducedinanyway,includingbutnotlimitedtophotocopy,photograph,magneticor
otherrecord,withouttheprioragreementandwrittenpermissionoftheauthor.
3
Copyright2001GeorgeOmura,,Worldrightsreserved
TheABCsofAutoLISPbyGeorgeOmura
4
Copyright2001GeorgeOmura,,Worldrightsreserved
TheABCsofAutoLISPbyGeorgeOmuraChapter1:IntroducingAutoLISPFeaturing
UnderstandingtheAutoLISPInterpreterandEvaluation
ExpressionsandArguments
VariablesandDataTypes
ManipulatingListswithFunctions
GetFunctions
Ifyouhaveneverprogrammedacomputerbefore,youmaythinkthatlearningAutoLISPwillbedifficult.Actually,
whenyouuseaprogramsuchasAutoCAD,youare,inasense,programmingyourcomputertocreateand
manipulateadatabase.AsyoubecomemorefamiliarwithAutoCAD,youmaybegintoexplorethecreationof
linetypesandhatchpatterns,forexample.Oryoumaycustomizeyourmenutoincludeyourownspecialized
functionsandmacros.(Macrosarelikescriptsthatthecomputerfollowstoperformapredeterminedsequenceof
commands.)Atthislevel,youaredelvingdeeperintotheworkingsofAutoCADandatthesametimeprogramming
yourcomputerinamoretraditionalsense.
UsingAutoLISPisreallyjustextendingyourknowledgeanduseofAutoCAD.Infact,onceyoulearnthebasic
syntaxofAutoLISP,youneedonlytofamiliarizeyourselfwithAutoLISP'sbuiltinfunctionstostartwritinguseful
programs.(AutoLISP'ssyntaxisthestandardorderofelementsinitsexpressions.)YoumightlookatAutoLISP
functionsasanextensiontoAutoCAD'slibraryofcommands.Themorefunctionsyouarefamiliarwith,thebetter
equippedyouareforusingtheprogrameffectively.
AutoLISPcloselyresemblesCommonLISP,themostrecentversionoftheoldestartificialintelligenceprogramming
languagestillinusetoday.AutoLISPisessentiallyapareddownversionofCommonLISPwithsomeadditional
featuresuniquetoAutoCAD.ManyconsiderLISPtobeoneoftheeasiestprogramminglanguagestolearn,partly
becauseofitssimplesyntax.SinceAutoLISPisasubsetofcommonLISP,itisthatmucheasiertolearn.
In this chapter, you will become familiar with some of the basic elements of AutoLISP by using AutoLISP directly
from the AutoCAD command prompt to perform a few simple operations. While doing this, you will be introduced to
someoftheconceptsyouwillneedtoknowtodevelopyourownAutoLISPapplications.
UnderstandingtheInterpreterandEvaluation
AutoLISPisaccessedthroughtheAutoLISPinterpreter.WhenyouenterdataattheAutoCADcommandprompt,
theinterpreterfirstreadsittodetermineifthedataisanAutoLISPformula.Ifthedataturnsouttobeintendedfor
AutoLISP,thenAutoLISPevaluatesit,andreturnsananswertothescreen.Thisprocessofreadingthecommand
prompt,evaluatingthedata,thenprintingtothescreen,occurswheneveranythingisenteredatthecommandprompt
5
Copyright2001GeorgeOmura,,Worldrightsreserved
TheABCsofAutoLISPbyGeorgeOmura
andisanimportantpartofhowAutoLISPfunctions.
Insomeways,theinterpreterislikeahandheldcalculator.Justaswithacalculator,theinformationyouwishtohave
AutoLISPevaluatemustfollowacertainorder.Forexample,theformula0.618plus1mustbeenteredasfollows:
(+0.6181)
Tryenteringtheaboveformulaatthecommandprompt.AutoLISPevaluatestheformula(+0.6181)andreturnsthe
answer,1.618,displayingitonthepromptline.
Thisstructure+0.6181enclosedbyparentheses,iscalledanexpressionanditisthebasicstructureforallAutoLISP
programs.EverythingintendedfortheAutoLISPinterpreter,fromthesimplestexpressiontothemostcomplex
program,mustbewrittenwiththisstructure.Theresultreturnedfromevaluatinganexpressioniscalledthevalueof
theexpression.
TheComponentsofanExpression
AnAutoLISPexpressionmustincludeanoperatorofsomesortfollowedbytheitemstobeoperatedon.Anoperator
isaninstructiontotakesomespecificactionsuchasaddingtwonumberstogetherordividingonenumberby
another.Examplesofmathematicaloperatorsincludetheplussign(+)foradditionandforwardslash(/)fordivision.
Wewilloftenrefertotheoperatorasafunctionandtheitemstobeoperatedonastheargumentstothefunctionor
simply,thearguments.So,intheexpression(+0.6181),the+isthefunctionandthe0.618and1arethearguments.
AllAutoLISPexpressions,nomatterwhatsize,followthisstructureandareenclosedbyparentheses.
Parenthesesareimportantelementsofanexpression.Allparenthesesmustalsobebalanced,thatis,foreachleft
parenthesis,theremustbearightparenthesis.IfyouenteranunbalancedexpressionintotheAutoLISPinterpreter,
yougetthefollowingprompt:
((_>
wherethenumberofparenthesestotheleftisthenumberofparenthesesrequiredtocompletetheexpression.Ifyou
seethisprompt,youmustenterthenumberofclosingparenthesesindicatedinordertoreturntothecommand
prompt.Inthisexample,youwouldneedtoentertworightparenthesestocompletetheexpression.
Double quotation marks enclosing text must also be carefully balanced. If an AutoLISP expression is unbalanced, it
can be quite difficult to complete it and exit AutoLISP. Figure 1.1 shows the components of the expression you just
entered.
6
Copyright2001GeorgeOmura,,Worldrightsreserved
TheABCsofAutoLISPbyGeorgeOmura
7
Copyright2001GeorgeOmura,,Worldrightsreserved
Figure1.1:ThepartsofandAutoLISPexpression
Notethatspacesareusedtoseparatethefunctionsandargumentsoftheexpression.Spacesarenotrequired
betweentheparenthesesandtheelementsoftheexpressionthoughyoucanaddspacestohelpimprovethe
readabilityofexpressionswhentheybecomecomplex.However,itisveryimportanttomaintainspacesbetweenthe
elementsoftheexpression.SpaceshelpbothyouandAutoLISPkeeptrackofwhereoneelementendsandanother
begins.
UsingArgumentsandExpressions
AutoLISPevaluateseverything,notjustexpressions,buttheargumentsinexpressionsaswell.Thismeansthatin
theaboveexample,AutoLISPevaluatesthenumbers0.618and1beforeitappliesthesenumberstotheplusoperator.
InAutoLISP,numbersevaluatetothemselves.ThismeansthatwhenAutoLISPevaluatesthenumber0.618,0.618is
returnedunchanged.SinceAutoLISPevaluatesallarguments,expressionscanalsobeusedasargumentstoa
function.
Forexample,enterthefollowingatthecommandprompt:
(/1(+0.6181))
Inthisexample,thedividefunction(/)isgiventwoargumentsnumber1andanexpression(+0.6181).Thistypeof
expressioniscalledacomplexornestedexpressionbecauseoneexpressioniscontainedwithinanother.Soinour
example,AutoLISPfirstevaluatestheargumentsoftheexpression,whicharetheexpression(+0.6181)andthe
number1.Itthenappliestheresultingvalueoftheexpressionandthenumber1tothedividefunctionandreturnsthe
answerof0.618047(seefigure1.2).
FunctionTArguments
BalancedParenthesis
TheABCsofAutoLISPbyGeorgeOmura
8
Copyright2001GeorgeOmura,,Worldrightsreserved
Figure1.2:Evaluationofanestedexpression
UsingVariables
Anothercalculatorlikecapabilityoftheinterpreterisitsabilitytoremembervalues.Youprobablyhaveacalculator
thathassomememory.Thiscapabilityallowsyoutostorethevalueofanequationforfutureuse.Inasimilarway,
youcanstorevaluesusingvariables.
Avariableislikeacontainerthatholdsavalue.Thatvaluecanchangeinthecourseofaprogram'soperation.A
simpleanalogytothisisthetitleofagovernmentposition.Thepositionofpresidentcouldbethoughtofasa
variable.Thisvariablecanbeassignedavalue,suchasRonaldReaganorBillClinton.
UnderstandingDataTypes
Variablescantakeonseveraltypesofvaluesordatatypes.Hereiswhatsomeofthesedatatypeslooklikein
AutoLISP.
Function
lII:06181))
LflArgumentsareevaluated
U11.618)I*IThenappliedtuthefunction
TheABCsofAutoLISPbyGeorgeOmura
DATATYPEEXAMPLE
Integer24
RealNumber0.618
String``20Feet6Inches''
List(4.50216.30110.0)
FileDescriptor<File:a620>
ObjectName<Objectname:60000014c>
SelectionSet<Selectionset:1>
SymbolsPoint1
SubrsSetq
Byseparatingdataintotypes,theinterpreterisbetterabletodeterminepreciselyhowtoevaluatethedataandkeep
programsrunningquickly.Also,acomputerstoresdifferenttypesofdatadifferently,andsodatatypeshelp
AutoLISPtomanageitsmemorymoreefficiently.Finally,datatypeshelpkeepyourprogrammingeffortsclearby
forcingyoutothinkofdataashavingcertaincharacteristics.Thefollowingdescriptionsgiveyouanideaofwhat
eachofthesedatatypesare.
IntegersandRealNumbers
Integersarewholenumbersfrom32768to+32767.Thevalueofanexpressioncontainingonlyintegersisalwaysan
integer.Forexample,thevalueoftheexpression(/252)is12.Thedecimalvalueisdroppedfromtheresultingvalue.
Realnumbersarenumbersthatincludeadecimalvalue.Ifthesameexpressionaboveiswrittenusingrealnumbers,(/
25.02.0),itsvaluewillbeexpressedastherealnumber12.5.Integershaveablackandwhitequalityaboutthem.24
willalwaysequal24.Realnumbers(sometimesreferredtoasreals),ontheotherhandcanbeabitlessdefinite.For
example,tworealvalues,24.001245781and24.001245782arenearlyidenticalbutarenotequal.Ifyouweretodropthe
lastdecimalplaceinboththesenumbers,thentheywouldbeequalvalues.Thisdefinitivequalityofintegersmakes
themmoresuitedtocertaintypesofuses,likecounting,whilerealnumbersarebettersuitedtosituationsthatrequire
exactingvaluessuchascoordinatevaluesandangles.Also,computationsperformedonintegersarefasterthan
thoseperformedonreals.
Youmayhavenoticedthatinourpreviousexamples,therealnumber0.618isprecededbyazeroandnotwrittenas
.618.InAutoLISP,realnumberswithvaluesbetween1.0and0.0mustbeginwithzero.Ifyoudonotfollowthisrule,
youwillgetanerrormessage.Enterthefollowingatthecommandprompt:
(+.6181)
9
Copyright2001GeorgeOmura,,Worldrightsreserved
TheABCsofAutoLISPbyGeorgeOmura
Thoughtheaboveexpressionlooksperfectlynormal,thefollowingerrormessageappears:
error:invaliddottedpair
MostbeginnersandevensomeexperiencedAutoLISPusersmightbecompletelybaffledbytheerrormessage.We
willlookatwhatdottedpairsarelaterinthisbookbutfornow,justkeepinmindthatrealvaluesbetween1.0and0.0
mustbeenteredwitha0precedingthedecimalpoint.
Strings
Thetermstringreferstotext.StringsareoftenusedaspromptsinAutoLISPexpressionsbuttheycanalsobe
manipulatedusingAutoLISP.Forexample,usingtheStrcatAutoLISPfunction,youcouldcombinetwostrings,
"thirtysevenfeet"and"sixinches",intoonestring"thirtysevenfeetsixinches".Tryenteringthis:
(strcat"thirtysevenfeet""sixinches")
Thefollowingisreturned:
"thirtysevenfeetsixinches"
Lists
Listsaredataelementsenclosedinparentheses.TheyarethebasicdatastructureinAutoLISP.Alistcanbemadeup
ofanynumberofintegers,realnumbers,strings,andevenotherlists.
Therearetwotypesoflists.Thoseintendedforevaluationandthoseintendedasrepositoriesfordata.Whenalist
containsafunctionasitsfirstelement,wecangenerallyassumethatitisanexpressionintendedforevaluation.Such
alistisoftenreferredtoasaform.Anexampleofalistasarepositoryofdataisalistthatrepresentsacoordinate
location.Forexample,thelist
(1.22.34.4)
containsthreeelements,anX,Y,andZcoordinate.Thefirstelement,1.2,isthexcoordinate,thesecondelement,2.3
istheycoordinate,andthethirdelement,4.4,isthezcoordinate.
FileDescriptors
AutoLISPallowsyoutoreadandwritetextfilestodisk.Filedescriptorsareusedinaprogramtoaccessfilesthat
havebeenopenedforprocessing.Youmightthinkofafiledescriptorasavariablerepresentingthefileinquestion.
WewilldiscussthisdatatypeinmoredetailinChapter7.
ObjectNames
EveryobjectinanAutoCADdrawinghasaname.Thenameisanalphanumericcodeuniquetothatobject.This
namecanbeaccessedbyAutoLISPandusedasameansofselectingindividualobjectsforprocessing.Object
namesareprovidedbyAutoCADandarenotuserdefinable.AlsoObjectnamescanchangefromonedrawing
sessiontoanother.
10
Copyright2001GeorgeOmura,,Worldrightsreserved