TheABCsofAutoLISPbyGeorgeOmura
1Copyright2001GeorgeOmura,,Worldrightsreserved
IntroductionOneofAutoCAD'sgreatestassetsisitsadaptability.YoucancontroljustabouteveryaspectofAutoCAD'soperationsfromtheappearanceofitsdrawingeditortoitsvarietyofmenus.Akeyelementofthisadaptabilityisitsbuiltinprogramminglanguage,AutoLISP.WithAutoLISP,youcanvirtuallywriteyourowncommandsorredefineothers.
YoucanthinkofAutoLISPasaverysophisticatedmacrobuildingfacility.(Simplemacrosarelikescriptsthatautomaterepetitivekeystrokes.)Youdon'tneedtobeaprogrammertouseAutoLISP.Infact,AutoLISPisdesignedsothateverydayusersofAutoCADcanstarttouseitafteraminimumoftraining.ThisbookmakesAutoLISPaccessibletoAutoCADuserswhoarelookingforawaytoenhanceandextendtheiruseofAutoCAD.
TheABCsofAutoLISPbyGeorgeOmuraW
hoshouldreadthisbookThisbookintroducesnonprogrammerstotheuseofAutoLISP.IfyouareanintermediatelevelAutoCADuser,interestedinlearningaboutthispowerfultool,thenthisisthebookforyou.IfyouarejustbeginningtolearnAutoCAD,thenyoushouldprobablybecomeabitmorefamiliarwithAutoCADbeforeattemptingtolearnAutoLISP.ThisbookassumesthatyouhaveatleastanintermediatelevelofexpertisewithAutoCADandareacquaintedwithsimpleWindowsoperations.
HowThisBookIsOrganizedThebookisdividedinto11chapters.ThefirstthreechaptersgiveyouanintroductiontoprogramminginAutoLISP.TheChapter1introducesyoutoAutoLISPbyshowingyouhowtouseitdirectlyfromtheAutoCADcommandprompt.TheChapter2showsyouhowtocreateandsaveprogramsinafile.Chapter3discusseswaysoforganizingyourprogrammingprojectsandhowtomanageyourcomputers'memory.
ThenextfourchaptersshowyouhowtouseAutoLISPtodoavarietyofeditingtasks.Chapter4discussesthefunctionsthatallowyoutoasktheuserforinput.Chapter5explainshowtobuilddecisionmakingcapabilitiesintoyourprograms.Chapter6showsyouhowtodealwithgeometricproblemsusingAutoCAD.Chapter7discussesthemanipulationoftext.
ThelastfourchaptersshowyouhowAutoCADandAutoLISPinteract.InChapter8,youwillseehowyoucancontrolmanyfacetsofAutoCADthroughAutoLISP.Chapter9delvesintolists,afundamentalcomponentofallAutoLISPprograms.Chapter10showsyouwaysofmodifyingAutoCADobjectsbydirectlyaccessingtheAutoCADdrawingdatabase.Andfinally,Chapter11looksatwaystodigdeeperintothedrawingdatabasetogetinformationoncomplexdrawingobjectslikepolylinesandblockattributes.
Inaddition,fiveappendicesareincludedasreferencematerialtothebook.Intheoriginalversionofthisbook,theseappendicescontainedtheresourcesindicatedbytheirtitle.Inthiselectronicversion,theseappendicesofferdirectionsonhowtofindinformationintheAutoCADhelpsystem.ThefirstthreeshowyouhowtofindinformationontheAutoCADmenustructure,AutoLISPerrormessages,andAutoCADgroupcodes.ThefourthappendixdescribeshowtofindinformatononthestandardAutoCADdimensionvariablesandsystemvariables.ThefifthappendixdescribeshowtofindinformatonontheTablegroupcodes.
2Copyright2001GeorgeOmura,,Worldrightsreserved
TheABCsofAutoLISPbyGeorgeOmura
HowtoUseThisBookEachchapteroffersexercisesandsampleprogramsthatdemonstratesomegeneralconceptregardingAutoLISP.Throughtheseexercises,thebookshowsyouhowprogramsdevelopfromideasintofinished,runningprograms.Also,theinformationyoulearninonechapterwillbuildonwhatyoulearnedinthepreviouschapter.Thisway,yourknowledgeofAutoLISPwillbeintegratedandcohesive,ratherthanfragmented.Forthisreason,thebestwaytousethisbookistoreadeachchapterinorderanddoalloftheexercises.Sincethetopicsareorientedtowardaccomplishingtasksratherthansimplyfocusingonindividualfunctions,youwillhaveagoodgraspofhowtouseAutoLISPinrealworldsituationsbytheendofthisbook.
WheretoFindtheLISPProgramsAsyoureadthechaptersanddotheexercise,youwillbeaskedtoenterprogramcodeintoafile.Ifyouareinahurry,youcancutandpastethecodedirectlyfromthechapteryouarereading.Thiswillsaveagooddealoftime,butmakesureyoustudythecodethatyoucutandpaste.Thisbookwasoriginallypublishedin1990bySybexInc.IthasbeenreproducedhereinanelectronicformatbytheAuthorforthebenefitofMasteringAutoCADreaderseverywhere.Enjoy....
Copyright2001GeorgeOmura,,Worldrightsreserved.Nopartofthispublicationmaybestoredinaretievalsystem,transmitted,orreproducedinanyway,includingbutnotlimitedtophotocopy,photograph,magneticorotherrecord,withouttheprioragreementandwrittenpermissionoftheauthor.
3Copyright2001GeorgeOmura,,Worldrightsreserved
TheABCsofAutoLISPbyGeorgeOmura
4Copyright2001GeorgeOmura,,Worldrightsreserved
TheABCsofAutoLISPbyGeorgeOmuraChapter1:IntroducingAutoLISPFeaturing
UnderstandingtheAutoLISPInterpreterandEvaluation
ExpressionsandArguments
VariablesandDataTypes
ManipulatingListswithFunctions
GetFunctions
Ifyouhaveneverprogrammedacomputerbefore,youmaythinkthatlearningAutoLISPwillbedifficult.Actually,whenyouuseaprogramsuchasAutoCAD,youare,inasense,programmingyourcomputertocreateandmanipulateadatabase.AsyoubecomemorefamiliarwithAutoCAD,youmaybegintoexplorethecreationoflinetypesandhatchpatterns,forexample.Oryoumaycustomizeyourmenutoincludeyourownspecializedfunctionsandmacros.(Macrosarelikescriptsthatthecomputerfollowstoperformapredeterminedsequenceofcommands.)Atthislevel,youaredelvingdeeperintotheworkingsofAutoCADandatthesametimeprogrammingyourcomputerinamoretraditionalsense.
UsingAutoLISPisreallyjustextendingyourknowledgeanduseofAutoCAD.Infact,onceyoulearnthebasicsyntaxofAutoLISP,youneedonlytofamiliarizeyourselfwithAutoLISP'sbuiltinfunctionstostartwritingusefulprograms.(AutoLISP'ssyntaxisthestandardorderofelementsinitsexpressions.)YoumightlookatAutoLISPfunctionsasanextensiontoAutoCAD'slibraryofcommands.Themorefunctionsyouarefamiliarwith,thebetterequippedyouareforusingtheprogrameffectively.
AutoLISPcloselyresemblesCommonLISP,themostrecentversionoftheoldestartificialintelligenceprogramminglanguagestillinusetoday.AutoLISPisessentiallyapareddownversionofCommonLISPwithsomeadditionalfeaturesuniquetoAutoCAD.ManyconsiderLISPtobeoneoftheeasiestprogramminglanguagestolearn,partlybecauseofitssimplesyntax.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.
UnderstandingtheInterpreterandEvaluationAutoLISPisaccessedthroughtheAutoLISPinterpreter.WhenyouenterdataattheAutoCADcommandprompt,theinterpreterfirstreadsittodetermineifthedataisanAutoLISPformula.IfthedataturnsouttobeintendedforAutoLISP,thenAutoLISPevaluatesit,andreturnsananswertothescreen.Thisprocessofreadingthecommandprompt,evaluatingthedata,thenprintingtothescreen,occurswheneveranythingisenteredatthecommandprompt
5Copyright2001GeorgeOmura,,Worldrightsreserved
TheABCsofAutoLISPbyGeorgeOmura
andisanimportantpartofhowAutoLISPfunctions.
Insomeways,theinterpreterislikeahandheldcalculator.Justaswithacalculator,theinformationyouwishtohaveAutoLISPevaluatemustfollowacertainorder.Forexample,theformula0.618plus1mustbeenteredasfollows:
(+0.6181)
Tryenteringtheaboveformulaatthecommandprompt.AutoLISPevaluatestheformula(+0.6181)andreturnstheanswer,1.618,displayingitonthepromptline.
Thisstructure+0.6181enclosedbyparentheses,iscalledanexpressionanditisthebasicstructureforallAutoLISPprograms.EverythingintendedfortheAutoLISPinterpreter,fromthesimplestexpressiontothemostcomplexprogram,mustbewrittenwiththisstructure.Theresultreturnedfromevaluatinganexpressioniscalledthevalueoftheexpression.
TheComponentsofanExpressionAnAutoLISPexpressionmustincludeanoperatorofsomesortfollowedbytheitemstobeoperatedon.Anoperatorisaninstructiontotakesomespecificactionsuchasaddingtwonumberstogetherordividingonenumberbyanother.Examplesofmathematicaloperatorsincludetheplussign(+)foradditionandforwardslash(/)fordivision.
Wewilloftenrefertotheoperatorasafunctionandtheitemstobeoperatedonastheargumentstothefunctionorsimply,thearguments.So,intheexpression(+0.6181),the+isthefunctionandthe0.618and1arethearguments.AllAutoLISPexpressions,nomatterwhatsize,followthisstructureandareenclosedbyparentheses.
Parenthesesareimportantelementsofanexpression.Allparenthesesmustalsobebalanced,thatis,foreachleftparenthesis,theremustbearightparenthesis.IfyouenteranunbalancedexpressionintotheAutoLISPinterpreter,yougetthefollowingprompt:
((_>
wherethenumberofparenthesestotheleftisthenumberofparenthesesrequiredtocompletetheexpression.Ifyouseethisprompt,youmustenterthenumberofclosingparenthesesindicatedinordertoreturntothecommandprompt.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.
6Copyright2001GeorgeOmura,,Worldrightsreserved
TheABCsofAutoLISPbyGeorgeOmura
7Copyright2001GeorgeOmura,,Worldrightsreserved
Figure1.1:ThepartsofandAutoLISPexpression
Notethatspacesareusedtoseparatethefunctionsandargumentsoftheexpression.Spacesarenotrequiredbetweentheparenthesesandtheelementsoftheexpressionthoughyoucanaddspacestohelpimprovethereadabilityofexpressionswhentheybecomecomplex.However,itisveryimportanttomaintainspacesbetweentheelementsoftheexpression.SpaceshelpbothyouandAutoLISPkeeptrackofwhereoneelementendsandanotherbegins.
UsingArgumentsandExpressionsAutoLISPevaluateseverything,notjustexpressions,buttheargumentsinexpressionsaswell.Thismeansthatintheaboveexample,AutoLISPevaluatesthenumbers0.618and1beforeitappliesthesenumberstotheplusoperator.InAutoLISP,numbersevaluatetothemselves.ThismeansthatwhenAutoLISPevaluatesthenumber0.618,0.618isreturnedunchanged.SinceAutoLISPevaluatesallarguments,expressionscanalsobeusedasargumentstoafunction.
Forexample,enterthefollowingatthecommandprompt:
(/1(+0.6181))
Inthisexample,thedividefunction(/)isgiventwoargumentsnumber1andanexpression(+0.6181).Thistypeofexpressioniscalledacomplexornestedexpressionbecauseoneexpressioniscontainedwithinanother.Soinourexample,AutoLISPfirstevaluatestheargumentsoftheexpression,whicharetheexpression(+0.6181)andthenumber1.Itthenappliestheresultingvalueoftheexpressionandthenumber1tothedividefunctionandreturnstheanswerof0.618047(seefigure1.2).
FunctionTArguments
BalancedParenthesis
TheABCsofAutoLISPbyGeorgeOmura
8Copyright2001GeorgeOmura,,Worldrightsreserved
Figure1.2:Evaluationofanestedexpression
UsingVariablesAnothercalculatorlikecapabilityoftheinterpreterisitsabilitytoremembervalues.Youprobablyhaveacalculatorthathassomememory.Thiscapabilityallowsyoutostorethevalueofanequationforfutureuse.Inasimilarway,youcanstorevaluesusingvariables.
Avariableislikeacontainerthatholdsavalue.Thatvaluecanchangeinthecourseofaprogram'soperation.Asimpleanalogytothisisthetitleofagovernmentposition.Thepositionofpresidentcouldbethoughtofasavariable.Thisvariablecanbeassignedavalue,suchasRonaldReaganorBillClinton.
UnderstandingDataTypesVariablescantakeonseveraltypesofvaluesordatatypes.HereiswhatsomeofthesedatatypeslooklikeinAutoLISP.
Function
lII:06181))LflArgumentsareevaluatedU11.618)I*IThenappliedtuthefunction
TheABCsofAutoLISPbyGeorgeOmura
DATATYPEEXAMPLE
Integer24
RealNumber0.618
String``20Feet6Inches''
List(4.50216.30110.0)
FileDescriptor
ObjectName
SelectionSet
SymbolsPoint1
SubrsSetq
Byseparatingdataintotypes,theinterpreterisbetterabletodeterminepreciselyhowtoevaluatethedataandkeepprogramsrunningquickly.Also,acomputerstoresdifferenttypesofdatadifferently,andsodatatypeshelpAutoLISPtomanageitsmemorymoreefficiently.Finally,datatypeshelpkeepyourprogrammingeffortsclearbyforcingyoutothinkofdataashavingcertaincharacteristics.Thefollowingdescriptionsgiveyouanideaofwhateachofthesedatatypesare.
IntegersandRealNumbersIntegersarewholenumbersfrom32768to+32767.Thevalueofanexpressioncontainingonlyintegersisalwaysaninteger.Forexample,thevalueoftheexpression(/252)is12.Thedecimalvalueisdroppedfromtheresultingvalue.
Realnumbersarenumbersthatincludeadecimalvalue.Ifthesameexpressionaboveiswrittenusingrealnumbers,(/25.02.0),itsvaluewillbeexpressedastherealnumber12.5.Integershaveablackandwhitequalityaboutthem.24willalwaysequal24.Realnumbers(sometimesreferredtoasreals),ontheotherhandcanbeabitlessdefinite.Forexample,tworealvalues,24.001245781and24.001245782arenearlyidenticalbutarenotequal.Ifyouweretodropthelastdecimalplaceinboththesenumbers,thentheywouldbeequalvalues.Thisdefinitivequalityofintegersmakesthemmoresuitedtocertaintypesofuses,likecounting,whilerealnumbersarebettersuitedtosituationsthatrequireexactingvaluessuchascoordinatevaluesandangles.Also,computationsperformedonintegersarefasterthanthoseperformedonreals.
Youmayhavenoticedthatinourpreviousexamples,therealnumber0.618isprecededbyazeroandnotwrittenas.618.InAutoLISP,realnumberswithvaluesbetween1.0and0.0mustbeginwithzero.Ifyoudonotfollowthisrule,youwillgetanerrormessage.Enterthefollowingatthecommandprompt:
(+.6181)
9Copyright2001GeorgeOmura,,Worldrightsreserved
TheABCsofAutoLISPbyGeorgeOmura
Thoughtheaboveexpressionlooksperfectlynormal,thefollowingerrormessageappears:
error:invaliddottedpair
MostbeginnersandevensomeexperiencedAutoLISPusersmightbecompletelybaffledbytheerrormessage.Wewilllookatwhatdottedpairsarelaterinthisbookbutfornow,justkeepinmindthatrealvaluesbetween1.0and0.0mustbeenteredwitha0precedingthedecimalpoint.
StringsThetermstringreferstotext.StringsareoftenusedaspromptsinAutoLISPexpressionsbuttheycanalsobemanipulatedusingAutoLISP.Forexample,usingtheStrcatAutoLISPfunction,youcouldcombinetwostrings,"thirtysevenfeet"and"sixinches",intoonestring"thirtysevenfeetsixinches".Tryenteringthis:
(strcat"thirtysevenfeet""sixinches")
Thefollowingisreturned:
"thirtysevenfeetsixinches"
ListsListsaredataelementsenclosedinparentheses.TheyarethebasicdatastructureinAutoLISP.Alistcanbemadeupofanynumberofintegers,realnumbers,strings,andevenotherlists.
Therearetwotypesoflists.Thoseintendedforevaluationandthoseintendedasrepositoriesfordata.Whenalistcontainsafunctionasitsfirstelement,wecangenerallyassumethatitisanexpressionintendedforevaluation.Suchalistisoftenreferredtoasaform.Anexampleofalistasarepositoryofdataisalistthatrepresentsacoordinatelocation.Forexample,thelist
(1.22.34.4)
containsthreeelements,anX,Y,andZcoordinate.Thefirstelement,1.2,isthexcoordinate,thesecondelement,2.3istheycoordinate,andthethirdelement,4.4,isthezcoordinate.
FileDescriptorsAutoLISPallowsyoutoreadandwritetextfilestodisk.Filedescriptorsareusedinaprogramtoaccessfilesthathavebeenopenedforprocessing.Youmightthinkofafiledescriptorasavariablerepresentingthefileinquestion.WewilldiscussthisdatatypeinmoredetailinChapter7.
ObjectNamesEveryobjectinanAutoCADdrawinghasaname.Thenameisanalphanumericcodeuniquetothatobject.ThisnamecanbeaccessedbyAutoLISPandusedasameansofselectingindividualobjectsforprocessing.ObjectnamesareprovidedbyAutoCADandarenotuserdefinable.AlsoObjectnamescanchangefromonedrawingsessiontoanother.
10Copyright2001GeorgeOmura,,Worldrightsreserved