AutoLISP Developer's Guide - Autodesk

Transcription

AutoCAD 2013AutoLISP Developer's GuideJanuary 2012

2012 Autodesk, Inc. All Rights Reserved. Except as otherwise permitted by Autodesk, Inc., this publication, or parts thereof, may notbe reproduced in any form, by any method, for any purpose.Certain materials included in this publication are reprinted with the permission of the copyright holder.TrademarksThe following are registered trademarks or trademarks of Autodesk, Inc., and/or its subsidiaries and/or affiliates in the USA and other countries:123D, 3ds Max, Algor, Alias, Alias (swirl design/logo), AliasStudio, ATC, AUGI, AutoCAD, AutoCAD Learning Assistance, AutoCAD LT, AutoCADSimulator, AutoCAD SQL Extension, AutoCAD SQL Interface, Autodesk, Autodesk Homestyler, Autodesk Intent, Autodesk Inventor, AutodeskMapGuide, Autodesk Streamline, AutoLISP, AutoSketch, AutoSnap, AutoTrack, Backburner, Backdraft, Beast, Beast (design/logo) Built withObjectARX (design/logo), Burn, Buzzsaw, CAiCE, CFdesign, Civil 3D, Cleaner, Cleaner Central, ClearScale, Colour Warper, Combustion,Communication Specification, Constructware, Content Explorer, Creative Bridge, Dancing Baby (image), DesignCenter, Design Doctor, Designer'sToolkit, DesignKids, DesignProf, DesignServer, DesignStudio, Design Web Format, Discreet, DWF, DWG, DWG (design/logo), DWG Extreme,DWG TrueConvert, DWG TrueView, DWFX, DXF, Ecotect, Evolver, Exposure, Extending the Design Team, Face Robot, FBX, Fempro, Fire, Flame,Flare, Flint, FMDesktop, Freewheel, GDX Driver, Green Building Studio, Heads-up Design, Heidi, Homestyler, HumanIK, IDEA Server, i-drop,Illuminate Labs AB (design/logo), ImageModeler, iMOUT, Incinerator, Inferno, Instructables, Instructables (stylized robot design/logo),Inventor,Inventor LT, Kynapse, Kynogon, LandXplorer, LiquidLight, LiquidLight (design/logo), Lustre, MatchMover, Maya, Mechanical Desktop, Moldflow,Moldflow Plastics Advisers, Moldflow Plastics Insight, Moldflow Plastics Xpert, Moondust, MotionBuilder, Movimento, MPA, MPA (design/logo),MPI, MPI (design/logo), MPX, MPX (design/logo), Mudbox, Multi-Master Editing, Navisworks, ObjectARX, ObjectDBX, Opticore, Pipeplus, Pixlr,Pixlr-o-matic, PolarSnap, PortfolioWall, Powered with Autodesk Technology, Productstream, ProMaterials, RasterDWG, RealDWG, Real-timeRoto, Recognize, Render Queue, Retimer, Reveal, Revit, RiverCAD, Robot, Scaleform, Scaleform GFx, Showcase, Show Me, ShowMotion,SketchBook, Smoke, Softimage, Softimage XSI (design/logo), Sparks, SteeringWheels, Stitcher, Stone, StormNET, Tinkerbox, ToolClip, Topobase,Toxik, TrustedDWG, U-Vis, ViewCube, Visual, Visual LISP, Voice Reality, Volo, Vtour, WaterNetworks, Wire, Wiretap, WiretapCentral, XSI.All other brand names, product names or trademarks belong to their respective holders.DisclaimerTHIS PUBLICATION AND THE INFORMATION CONTAINED HEREIN IS MADE AVAILABLE BY AUTODESK, INC. "AS IS." AUTODESK, INC. DISCLAIMSALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY ORFITNESS FOR A PARTICULAR PURPOSE REGARDING THESE MATERIALS.

ContentsChapter 1Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1AutoLISP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1About Related AutoLISP Documents . . . . . . . . . . . . . . . . . 2Chapter 2Using the AutoLISP Language . . . . . . . . . . . . . . . . . . . 3AutoLISP Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3AutoLISP Expressions . . . . . . . . . . . . . . . . . . . . . . . . . 3AutoLISP Function Syntax . . . . . . . . . . . . . . . . . . . 5AutoLISP Data Types . . . . . . . . . . . . . . . . . . . . . . . . . 6Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Reals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Selection Sets . . . . . . . . . . . . . . . . . . . . . . . . . . 8Entity Names . . . . . . . . . . . . . . . . . . . . . . . . . . 8File Descriptors . . . . . . . . . . . . . . . . . . . . . . . . . 9Symbols and Variables . . . . . . . . . . . . . . . . . . . . 10AutoLISP Program Files . . . . . . . . . . . . . . . . . . . . . . . 11Formatting AutoLISP Code . . . . . . . . . . . . . . . . . . 11Comments in AutoLISP Program Files . . . . . . . . . . . . 11AutoLISP Variables . . . . . . . . . . . . . . . . . . . . . . . . . 12Displaying the Value of a Variable . . . . . . . . . . . . . . 13iii

Nil Variables . . . . . . . . . . . . . . . . . . . . . . .Predefined Variables . . . . . . . . . . . . . . . . . . .Number Handling . . . . . . . . . . . . . . . . . . . . . . .String Handling . . . . . . . . . . . . . . . . . . . . . . . .Basic Output Functions . . . . . . . . . . . . . . . . . . . .Displaying Messages . . . . . . . . . . . . . . . . . .Control Characters in Strings . . . . . . . . . . . . . .Wild-Card Matching . . . . . . . . . . . . . . . . . .Equality and Conditional . . . . . . . . . . . . . . . . . . .List Handling . . . . . . . . . . . . . . . . . . . . . . . . .Point Lists . . . . . . . . . . . . . . . . . . . . . . . .Dotted Pairs . . . . . . . . . . . . . . . . . . . . . . .Symbol and Function Handling . . . . . . . . . . . . . . .Using defun to Define a Function . . . . . . . . . . .C:XXX Functions . . . . . . . . . . . . . . . . . . . .Local Variables in Functions . . . . . . . . . . . . . .Functions with Arguments . . . . . . . . . . . . . . .Error Handling in AutoLISP . . . . . . . . . . . . . . . . . .Using the *error* Function . . . . . . . . . . . . . . .Catching Errors and Continuing Program Execution .Using AutoLISP to Communicate with AutoCAD . . . . . . . . .Accessing Commands and Services . . . . . . . . . . . . . .Command Submission . . . . . . . . . . . . . . . . .System and Environment Variables . . . . . . . . . . .Configuration Control . . . . . . . . . . . . . . . . .Display Control . . . . . . . . . . . . . . . . . . . . . . . .Control of Graphics and Text Windows . . . . . . . .Control of Low-Level Graphics . . . . . . . . . . . . .Getting User Input . . . . . . . . . . . . . . . . . . . . . .The getxxx Functions . . . . . . . . . . . . . . . . . .Control of User-Input Function Conditions . . . . . .Geometric Utilities . . . . . . . . . . . . . . . . . . . . . .Object Snap . . . . . . . . . . . . . . . . . . . . . . .Text Extents . . . . . . . . . . . . . . . . . . . . . . .Conversions . . . . . . . . . . . . . . . . . . . . . . . . . .String Conversions . . . . . . . . . . . . . . . . . . .Angular Conversion . . . . . . . . . . . . . . . . . . .ASCII Code Conversion . . . . . . . . . . . . . . . . .Unit Conversion . . . . . . . . . . . . . . . . . . . .Coordinate System Transformations . . . . . . . . . .File Handling . . . . . . . . . . . . . . . . . . . . . . . . .File Search . . . . . . . . . . . . . . . . . . . . . . . .Device Access and Control . . . . . . . . . . . . . . . . . .Accessing User Input . . . . . . . . . . . . . . . . . .Using AutoLISP to Manipulate AutoCAD Objects . . . . . . . . .Selection Set Handling . . . . . . . . . . . . . . . . . . . .iv Contents. 13. 13. 14. 14. 16. 17. 18. 20. 21. 21. 23. 26. 28. 28. 30. 34. 36. 38. 39. 41. 42. 42. 43. 47. 47. 47. 48. 48. 49. 49. 52. 55. 56. 56. 61. 61. 64. 65. 67. 70. 72. 73. 74. 74. 74. 75

Selection Set Filter Lists . . . . . . . . . . . . . . . . . . . . 77Passing Selection Sets between AutoLISP and ObjectARXApplications . . . . . . . . . . . . . . . . . . . . . . . . . 85Object Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . 86Entity Name Functions . . . . . . . . . . . . . . . . . . . . 86Entity Data Functions . . . . . . . . . . . . . . . . . . . . . 92Entity Data Functions and the Graphics Screen . . . . . . . 102Old-Style Polylines and Lightweight Polylines . . . . . . . 103Non-Graphic Object Handling . . . . . . . . . . . . . . . 104Extended Data - xdata . . . . . . . . . . . . . . . . . . . . . . . 106Organization of Extended Data . . . . . . . . . . . . . . . 107Registration of an Application . . . . . . . . . . . . . . . . 109Retrieval of Extended Data . . . . . . . . . . . . . . . . . 110Attachment of Extended Data to an Entity . . . . . . . . . 111Management of Extended Data Memory Use . . . . . . . . 112Handles in Extended Data . . . . . . . . . . . . . . . . . . 112Xrecord Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 113Symbol Table and Dictionary Access . . . . . . . . . . . . . . . 114Symbol Tables . . . . . . . . . . . . . . . . . . . . . . . . 114Dictionary Entries . . . . . . . . . . . . . . . . . . . . . . 116Chapter 3Appendixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119AutoLISP Function Synopsis . . . . . . . . . . . . . . . . . . .Category Summary . . . . . . . . . . . . . . . . . . . . .Basic Functions . . . . . . . . . . . . . . . . . . . . . . .Application-Handling Functions . . . . . . . . . .Arithmetic Functions . . . . . . . . . . . . . . . .Equality and Conditional Functions . . . . . . . .Error-Handling Functions . . . . . . . . . . . . . .Function-Handling Functions . . . . . . . . . . . .List Manipulation Functions . . . . . . . . . . . .String-Handling Functions . . . . . . . . . . . . .Symbol-Handling Functions . . . . . . . . . . . . .Utility Functions . . . . . . . . . . . . . . . . . . . . . .Conversion Functions . . . . . . . . . . . . . . . .Device Access Functions . . . . . . . . . . . . . . .Display Control Functions . . . . . . . . . . . . . .File-Handling Functions . . . . . . . . . . . . . . .Geometric Functions . . . . . . . . . . . . . . . .Query and Command Functions . . . . . . . . . .User Input Functions . . . . . . . . . . . . . . . .Selection Set, Object, and Symbol Table Functions . . . .Extended Data-Handling Functions . . . . . . . . .Object-Handling Functions . . . . . . . . . . . . .Selection Set Manipulation Functions . . . . . . . .Symbol Table and Dictionary-Handling Functions . 119. 119. 121. 121. 122. 125. 126. 127. 128. 131. 133. 134. 134. 135. 136. 137. 139. 139. 141. 142. 143. 143. 145. 146Contents v

Memory Management Functions . . . .VLX Namespace Functions . . . . . . .Namespace Communication Functions .Property List (Plist) Functions . . . . . .AutoLISP Error Codes . . . . . . . . . . . . .Error Codes . . . . . . . . . . . . . . . . 147. 147. 148. 149. 149. 149Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157vi Contents

1IntroductionIntroduction For years, AutoLISP has set the standard for customizing AutoCAD onWindows . AutoCAD also supports AutoLISP, but does not support many of the Visual LISP functions or the Microsoft ActiveX Automation interface.AutoCAD does not have an integrated development environment like AutoCADon Windows does, so the creation and editing of LSP files must be done withtext editor such as TextEdit.AutoLISPAutoLISP is a programming language designed for extending and customizingthe functionality of AutoCAD. It is based on the LISP programming language,whose origins date back to the late 1950s. LISP was originally designed for usein Artificial Intelligence (AI) applications, and is still the basis for many AIapplications.AutoLISP was introduced as an application programming interface (API) inAutoCAD Release 2.1, in the mid-1980s. LISP was chosen as the initial AutoCADAPI because it was uniquely suited for the unstructured design process ofAutoCAD projects, which involved repeatedly trying different solutions to designproblems.Developing AutoLISP programs for AutoCAD is done by writing code in a texteditor, then loading the code into AutoCAD and running it. Debugging yourprogram is handled by adding statements to print the contents of variables atstrategic points in your program. You must figure out where in your programto do this, and what variables you need to look at. If you discover you do nothave enough information to determine the error, you must go back and change1

the code by adding more debugging points. And finally, when you get theprogram to work correctly, you need to either comment out or remove thedebugging code you added.About Related AutoLISP DocumentsIn addition to the AutoLISP Reference, several other AutoCAD publications maybe required by users building applications with AutoLISP: AutoCADCustomization Guide contains basic information on creatingcustomized AutoCAD applications. For example, it includes informationon creating customized user interface elements, linetypes, and hatchpatterns. The Customization Guide is available through the AutoCAD andHelp menu on the Mac OS menu bar. The DXF Reference describes drawing interchange format (DXFTM) and theDXF group codes that identify attributes of AutoCAD objects.The DXF Reference is not included when you install AutoCAD. To obtainthe manual, download the DXF Reference from www.autodesk.com. The ObjectARX Reference contains information on using ObjectARX todevelop customized AutoCAD applications. AutoCAD reactor functionalityis implemented through ObjectARX. If you develop AutoLISP applicationsthat implement reactor functions, you may want to refer to this manual.The ObjectARX Reference is not included when you install AutoCAD. Toobtain the manual, download the ObjectARX SDK (Software DevelopmentKit) from www.autodesk.com.2 Chapter 1 Introduction

2Using the AutoLISP LanguageAutoLISP BasicsYou can use number, string, and list-handling functions to customize AutoCAD. This chapter introduces the basic concepts of the AutoLISP programminglanguage. It describes the core components and data types used in AutoLISP,and presents examples of simple number-, string-, output-, and list-handlingfunctions.AutoLISP code does not need to be compiled, so you can enter the code at aCommand line and immediately see the results.AutoLISP ExpressionsAn AutoLISP program consists of a series of expressions. AutoLISP expressionshave the following form:(functionarguments)Each expression begins with an open (left) parenthesis and consists of a functionname and optional arguments to that function. Each argument can also be anexpression. The expression ends with a right parenthesis. Every expressionreturns a value that can be used by a surrounding expression. The value of thelast interpreted expression is returned to the calling expression.For example, the following code example involves three functions:3

(fun1 (fun2arguments)(fun3arguments))If you enter this code at the AutoCAD Command prompt, the AutoCADAutoLISP interpreter processes the code. The first function, fun1, has twoarguments, and the other functions, fun2 and fun3, each have one argument.The functions fun2 and fun3 are surrounded by function fun1, so their returnvalues are passed to fun1 as arguments. Function fun1 evaluates the twoarguments and returns the value to the window from which you entered thecode.The following example shows the use of the * (multiplication) function, whichaccepts one or more numbers as arguments:(* 2 27)54Because this code example has no surrounding expression, AutoLISP returnsthe result to the window from which you entered the code.Expressions nested within other expressions return their result to thesurrounding expression. The following example uses the result from the (addition) function as one of the arguments for the * (multiplication) function.(* 2 ( 5 10))30If you enter the incorrect number of close (right) parentheses, AutoLISP displaysthe following prompt:( The number of open parentheses in this prompt indicates how many levelsof open parentheses remain unclosed. If this prompt appears, you must enterthe required number of close parentheses for the expression to be evaluated.(* 2 ( 5 10(( ))304 Chapter 2 Using the AutoLISP Language

A common mistake is to omit the closing quotation mark (") in a text string,in which case the close parentheses are interpreted as part of the string andhave no effect in resolving the open parentheses. To correct this condition,press Shift Esc to cancel the function, then re-enter it correctly.AutoLISP Function SyntaxIn this guide, the following conventions describe the syntax for AutoLISPfunctions:In this example, the foo function has one required argument, string, and oneoptional argument, number. Additional number arguments can be provided.Frequently, the name of the argument indicates the expected data type. Theexamples in the following table show both valid and invalid calls to the foofunction.Valid and invalid function call examplesValid callsInvalid calls(foo "catch")(foo 44 13)(foo "catch" 22)(foo "fi" "foe" 44 13)(foo "catch" 22 31)(foo)AutoLISP Basics 5

AutoLISP Data TypesAutoLISP expressions are processed according to the order and data type ofthe code within the parentheses. Before you can fully utilize AutoLISP, youmust understand the differences among the data types and how to use them.IntegersIntegers are whole numbers that do not contain a decimal point. AutoLISPintegers are 32-bit signed numbers with values ranging from 2,147,483,647to -2,147,483,648. (Note, however, that the getint function only accepts 16-bitnumbers ranging from 32767 to -32678.) When you explicitly use an integerin an AutoLISP expression, that value is known as a constant. Numbers suchas 2, -56, and 1,200,196 are valid AutoLISP integers.If you enter a number that is greater than the maximum integer allowed(resulting in integer overflow), AutoLISP converts the integer to a real number.However, if you perform an arithmetic operation on two valid integers, andthe result is greater than the maximum allowable integer, the resulting numberwill be invalid. The following examples illustrate how AutoLISP handles integeroverflow.The largest positive integer value retains its specified value:21474836472147483647If you enter an integer that is greater than the largest allowable value, AutoLISPreturns the value as a real:21474836482.14748e 009An arithmetic operation involving two valid integers, but resulting in integeroverflow, produces an invalid result:( 2147483646 3)-21474836476 Chapter 2 Using the AutoLISP Language

In this example the result is clearly invalid, as the addition of two positivenumbers results in a negative number. But note how the following operationproduces a valid result:( 2147483648 2)2.14748e 009In this instance, AutoLISP converts 2147483648 to a valid real before adding2 to the number. The result is a valid real.The largest negative integer value retains its specified value:-2147483647-2147483647If you enter a negative integer larger than the greatest allowable negativevalue, AutoLISP returns the value as a real:-2147483648-2.14748e 009The following operation concludes successfully, because AutoLISP first convertsthe overflow negative integer to a valid real:(- -2147483648 1)-2.14748e 009RealsA real is a number containing a decimal point. Numbers between -1 and 1must contain a leading zero. Real numbers are stored in double-precisionfloating-point format, providing at least 14 significant digits of precision.Reals can be expressed in scientific notation, which has an optional e or Efollowed by the exponent of the number (for example, 0.0000041 is the sameas 4.1e-6). Numbers such as 3.1, 0.23, -56.123, and 21,000,000.0 are validAutoLISP reals.AutoLISP Basics 7

StringsA string is a group of characters surrounded by quotation marks. Within quotedstrings the backslash (\) character allows control characters (or escape codes)to be included. When you explicitly use a quoted string in an AutoLISPexpression, that value is known as a literal string or a string constant.Examples of valid strings are “string 1” and “\nEnter first point:”.ListsAn AutoLISP list is a group of related values separated by spaces and enclosedin parentheses. Lists provide an efficient method of storing numerous relatedvalues. AutoCAD expresses 3D points as a list of three real numbers.Examples of lists are (1.0 1.0 0.0), (“this” “that” “the other”), and (1 “ONE”).Selection SetsSelection sets are groups of one or more objects (entities). You can interactivelyadd objects to, or remove objects from, selection sets with AutoLISP routines.The following example uses the ssget function to return a selection setcontaining all the objects in a drawing.(ssget "X") Selection set: 1 Entity NamesAn entity name is a numeric label assigned to objects in a drawing. It is actuallya pointer into a file maintained by AutoCAD, and can be used to find theobject's database record and its vectors (if they are displayed). This label canbe referenced by AutoLISP functions to allow selection of objects for processingin various ways. Internally, AutoCAD refers to objects as entities.The following example uses the entlast function to get the name of the lastobject entered into the drawing.8 Chapter 2 Using the AutoLISP Language

(entlast) Entity name: 27f0540 Entity names assigned to objects in a drawing are only in effect during thecurrent editing session. The next time you open the drawing, AutoCAD assignsnew entity names to the objects. You can use an object's handle to refer to itfrom one editing session to another; see Entity Handles and Their Uses (page87) for information on using handles.File DescriptorsA file descriptor is a pointer to a file opened by the AutoLISP open function.The open function returns this pointer as an alphanumeric label. You supplythe file descriptor as an argument to other AutoLISP functions that read orwrite to the file.The following example opens the myinfo.dat file for reading. The open functionreturns the file descriptor:(setq file1 (open "/myinfo.dat" "r") )# file "/myinfo.dat" In this example, the file descriptor is stored in the file1variable.Files remain open until you explicitly close them in your AutoLISP program.The close function closes a file. The following code closes the file whose filedescriptor is stored in the file1 variable:(close file1)nilAutoLISP Basics 9

Symbols and VariablesAutoLISP uses symbols to refer to data. Symbol names are not case sensitiveand may consist of any sequence of alphanumeric and notation characters,except the following:Characters restricted from symbol names((Open Parenthesis))(Close Parenthesis).(Period)'(Apostrophe)"(Quote Symbol);(Semicolon)A symbol name cannot consist only of numeric characters.Technically, AutoLISP applications consist of either symbols or constant values,such as strings, reals, and integers. For the sake of clarity, this guide uses theterm symbol to refer to a symbol name that stores static data, such as built-inand user-defined functions. The term variable is used to refer to a symbol namethat stores program data. The following example uses the setq function toassign the string value "this is a string" to the str1 variable:(setq str1 "this is a string")"this is a string"Help yourself and others who need to read your code. Choose meaningfulnames for your program symbols and variables.10 Chapter 2 Using the AutoLISP Language

AutoLISP Program FilesAlthough you can enter AutoLISP code at the AutoCAD Command prompt,testing and debugging a series of instructions are considerably easier whenyou save AutoLISP code in a file rather than re-entering it each time you makea refinement. AutoLISP source code is usually stored in ASCII text files withan .lsp extension. However, you can load AutoLISP code from any ASCII textfile.Formatting AutoLISP CodeThe extensive use of parentheses in AutoLISP code can make it difficult toread. The traditional technique for combatting this confusion is indentation.The more deeply nested a line of code is, the farther to the right you positionthe line.Spaces in AutoLISP CodeIn AutoLISP, multiple spaces between variable names, constants, and functionnames are equivalent to a single space. The end of a line is also treated as asingle space.The following two expressions produce the same result:(setq test1 123 test2 456)(setqtest1 123test2 456)Comments in AutoLISP Program FilesIt is good practice to include comments in AutoLISP program files. Commentsare useful to both the programmer and future users who may need to revisea program to suit their needs. Use comments to do the following: Give a title, authorship, and creation date Provide instructions on using a routine Make explanatory notes throughout the body of a routineAutoLISP Basics 11

Make notes to yourself during debuggingComments begin with one or more semicolons (;) and continue through theend of the line.; This entire line is a comment(setq area (* pi r r)) ; Compute area of circleAny text within ; . ; is ignored. Therefore, comments can be includedwithin a line of code or extend for multiple lines. This type of comment isknown as an in-line comment.(setq tmode ; some note here ; (getvar "tilemode"))The following example shows a comment that continues for multiple lines:(setvar "orthomode" 1) ; comment starts hereand continues to this line,but ends way down here ; (princ "\nORTHOMODE set On.")It is recommended that you use comments liberally when writing AutoLISPprograms.AutoLISP VariablesAn AutoLISP variable assumes the data type of the value assigned to it. Untilthey are assigned new values, variables retain their original values. You usethe AutoLISP setq function to assign values to variables.(setqvariable name1 value1 [variable name2 value2 .])The setq function assigns the specified value to the variable name given. Itreturns the value as its function result.(setq val 3 abc 3.875)3.875(setq layr "EXTERIOR-WALLS")"EXTERIOR-WALLS"12 Chapter 2 Using the AutoLISP Language

Displaying the Value of a VariableTo display the value of a variable from the AutoCAD Command prompt, youmust precede the variable name with an exclamation point (!). For example:!abc3.875Nil VariablesAn AutoLISP variable that has not been assigned a value is said to be nil. Thisis different from blank, which is considered a character string, and differentfrom 0, which is a number. So, in addition to checking a variable for its currentvalue, you can test to determine if the variable has been assigned a value.Each variable consumes a small amount of memory, so it is good programmingpractice to reuse variable names or set variables to nil when their values areno longer needed. Setting a variable to nil releases the memory used to storethat variable's value. If you no longer need the val variable, you can releaseits value from memory with the following expression:(setq val nil)nilAnother efficient programming practice is to use local variables wheneverpossible. See Local Variables in Functions (page 34) on this topic.Predefined VariablesThe following predefined variables are commonly used in AutoLISPapplications:PAUSE Defined as a string consisting of a double backslash (\\) character. Thisvariable is used with the command function to pause for user input.PI Defined as the constant p (pi). It evaluates to approximately 3.14159.T Defined as the constant T. This is used as a non-nil value.AutoLISP Basics 13

NOTE You can change the value of these variables with the setq function. However,other applications might rely on their values being consistent; therefore, it isrecommended that you do not modify these variables.Number HandlingAutoLISP provides functions for working with integers and real numbers. Inaddition to performing complex mathematical computations in applications,you can use the number-handling functions to help you in your daily use ofAutoCAD. If you are drawing a steel connection detail that uses a 2.5" boltthat is 0.5" in diameter, how many threads are there if the bolt has 13 threadsper inch?(* 2.5 13)32.5The arithmetic functions that have a number argument (as opposed to num orangle, for example) return different values if you provide integers or reals asarguments. If all arguments are integers, the value returned is an integer.However, if one or all the arguments are reals, the value returned is a real. Toensure your application passes real values, be certain at least one argument isa real.(/ 12 5)2(/ 12.0 5)2.4A complete list of number-handling functions is in AutoLISP Function Synopsis,(page 119) under the heading Arithmetic Functions. (page 122) These functionsare described in the AutoLISP Reference.String HandlingAutoLISP provides functions for working with string values. For example, thestrcase function returns the conversion of all alphabetic characters in a stringto uppercase or lowercase. It accepts two arguments: a string and an optional14 Chapter 2 Using the AutoLISP Language

argument that specifies the case in which the characters are returned. If theoptional second argument is omitted, it evaluates to nil and strcase returnsthe characters converted to uppercase.(strcase "This is a TEST.")"THIS IS A TEST."If you provide a second argument of T, the characters are returned as lowercase.AutoLISP provides the predefined variable T to use in similar situations wherea non-nil value is used as a type of true/false toggle.(strcase "This is a TEST." T)"this is a test."The strcat function combines multiple strings into a single string value. Thisis useful for placing a variable string within a constant string. The followingcode sets a variable to a string value and then uses strcat to insert that stringinto the middle of another string.(setq str "BIG") (setq bigstr (strcat "This is a " str " test."))"This is a BIG test."If the variable bigstr is set to the preceding string value, you can use thestrlen function to find out the number of characters (including spaces) in thatstring.(strlen bigstr)19The

(fun1 (fun2 arguments)(fun3 arguments)) If you enter this code at the AutoCAD Command prompt, the AutoCAD AutoLISP interpreter processes the code. The first function, fun1, has two arguments, and the other functions, fun2 and fun3, each have one argument. The functions fun2 and fun3 are surrounded by function fun1, so their return values are passed to fun1 as arguments.