Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AutoCAD & AutoCAD LT All-In-One Desk Reference For Dummies (2006)

.pdf
Скачиваний:
90
Добавлен:
17.08.2013
Размер:
17.7 Mб
Скачать

692 Creating a Basic Program

An example of creating a custom function with the Defun function is

(defun RTD (rad)

(* (/ rad PI) 180)

)

The preceding example shows a custom function named RTD with a single argument named rad. (RTD is short for Radians to Degrees.) If you take a look at the expressions, you can see that there is a single expression using nested expressions. To convert a radians value, the value of rad is divided by the value of PI and then multiplied by 180.

So if you typed in RTD at the command line, you would get a warning about the command not being found. This is because it is a function, so it must be typed in at the command line using opening and closing parentheses like this: (RTD 1.57079633). After the RTD function is evaluated, a value of 90 is returned to the command line.

There are three predefined variables in AutoLISP: PI, T, and PAUSE. PI holds the value 3.14159, T holds a non-nil value and evaluates to T, and PAUSE is used in conjunction with the Command function to wait for the user to supply some input via the mouse or keyboard.

An example of creating a custom command with the Defun function is

(defun c:HL2 ()

(command “.line” “0,0” “2,0” “”)

)

The preceding example shows a custom command named HL2 with no arguments. HL2 is short for Horizontal Line of 2 units. If you take a look at the expressions, you can see that there is a single expression with no nesting, but it is using multiple arguments. The function Command is used, which allows you to automate tasks using the built-in AutoCAD commands.

In this case, the command that is being used is LINE. A line is being generated from the coordinates 0,0 to 2,0. Because only a single line with a start and end point is required, “” (two double quote marks with no text between) is used as the last argument to end the LINE command. “” is like pressing Enter on the keyboard. To run the custom command, all you need to do is type HL2 at the command line. You do not need to add opening and closing parentheses as you did to use the function.

Creating your first AutoLISP program

It’s time to put everything together and create your first custom command. This example has you create a new AutoLISP file, add a new command, and then load it into AutoCAD:

Creating a Basic Program 693

1.From the Tools menu in AutoCAD, choose AutoLISP

Visual LISP Editor.

AutoCAD launches the Visual LISP Editor.

2.From the Files menu in the Visual LISP Editor, choose New File.

An empty Text Window titled <Untitiled-0> is created.

3.From the Files menu in the Visual LISP Editor, choose Save As.

The Save As dialog box is displayed, allowing you to save the contents of the current Text window.

4.In the Save As dialog box, make sure the Save As Type drop-down list is set to Lisp Source File and enter MyStuff.LSP in the File Name text box. Then specify the save to location by selecting My Documents from the Save In drop-down list.

5.Click Save.

The contents of the Text window are written to a file named MyStuff.LSP located in the My Documents folder.

6.In the Text Window titled MyStuff.LSP, enter the following code:

;;Defines a two letter command to start a Zoom Window (defun c:ZW ( )

(command “.Zoom” “Window”)

)

7.From the Files menu in the Visual LISP Editor, choose Save.

The new command is saved out to the MyStuff.LSP file.

8.Switch back to AutoCAD by clicking the icon in the Windows taskbar area or select the Windows menu in the Visual LISP Editor and choose Activate AutoCAD.

Focus should now be shifted to the AutoCAD application window.

9.At the command line, type ZW.

This error message should be displayed in the command line window because the AutoLISP file hasn’t been loaded yet:

Unknown command “ZW”. Press F1 for help.

10.Switch back to the Visual LISP Editor by clicking on its icon in the Windows taskbar area, or select the Tools menu in AutoCAD and choose AutoLISP Visual LISP Editor.

Focus should now be shifted to the Visual LISP Editor.

11.From the Tools menu in the Visual LISP editor, choose Load Text in Editor.

The custom command should now be ready to use in AutoCAD.

Book X

Chapter 3

AutoLISP

Introducing

694 More Than Just the Essentials of AutoLISP

12.Switch back to AutoCAD and type ZW again.

This time, no error message is displayed and the ZOOM command starts with the Window option automatically. The first prompt that is displayed is Specify first corner.

13.Select two points on-screen to complete the Window option of the ZOOM command.

More Than Just the Essentials of AutoLISP

After you have a good foundation of what it takes to create an AutoLISP file and create a custom command, it’s time to introduce you to some more functions. AutoLISP can perform math calculations, string manipulation, and much more. All these are important in adding functionality to your custom programs.

Supported data types

AutoLISP is a programming language, so it uses data types to represent certain types of information. Data types play a role in how your application exchanges information with functions, and even with AutoCAD and the user. Table 3-3 shows the different data types that are available in AutoLISP.

Table 3-3

Data Types in AutoLISP

Data Type

Brief Description

Examples

 

 

 

Integer

A whole number with no decimal place, and

10

 

values fall in the range of –32,768 and 32,767.

 

 

 

 

Real

Any number with a decimal place and 14

1.0, 0.23451, .5

 

significant places of precision.

 

 

 

 

String

Any number of alphanumeric characters

“Hello”

 

enclosed in double quotes.

 

 

 

 

List

An expression enclosed in parentheses.

(0.5 0.5 0),

 

 

(“Hello” “World”),

 

 

(1 “Hello”)

 

 

 

Symbol

Variables used to hold data.

PI, abc, retVal

 

 

 

Selection

A valid selection set to hold references to

<Selection set: 1>

set

entities.

 

 

 

 

Entity

A valid entity name used to reference

<Entity name:

name

an individual entity in the drawing.

0cf0121>

 

 

 

VLA-object

A valid COM object used with ActiveX

#<VLA-OBJECT

 

Automation.

IAcadApplication

 

 

00c2db8c>

 

 

 

File

A reference point to an open file in memory.

#<file “acad.pgp”>

descriptor

 

 

 

 

 

More Than Just the Essentials of AutoLISP 695

Math functions

Because AutoCAD is a drafting program, you most likely find yourself needing to work with numbers from time to time. AutoLISP math functions come in a variety of different forms, from standard math functions like + (addition) and (subtraction) to much more complex functions, such as sin (sine) and atan (arctangent).

Table 3-4 shows some of the different math functions that are available in AutoLISP.

Table 3-4

Some of the Basic Math Functions

 

Function Syntax

 

Description

Result

 

 

 

(+ [number number ...])

Sums all numbers together and

3.5

 

 

returns the value.

 

 

 

Example:

 

 

 

(+ 1 2.5)

 

 

 

 

(- [number number ...])

Subtracts all the numbers from

0.75

 

 

the first one and returns the value.

 

 

 

Example:

 

 

 

(- 1 0.25)

 

 

 

 

(* [number number ...])

Multiplies all the numbers

15

 

 

together and returns the value.

 

 

 

Example:

 

 

 

(* 1 3 5)

 

 

 

 

(/ [number number ...])

Divides the first number by the

0

 

 

product of all the remaining

 

 

 

numbers and returns the value.

 

 

 

Example:

 

 

 

(/ 2 5)

 

 

 

 

 

(abs number)

 

Returns the absolute value.

1.34

 

 

Example:

 

 

 

(abs -1.34)

 

 

 

 

 

(sqrt number)

 

Returns the square root of the

1.73205

 

 

number.

 

Example:

(sqrt 3)

Book X

Chapter 3

AutoLISP

Introducing

696 More Than Just the Essentials of AutoLISP

String functions

Strings provide feedback to the user in the form of error messages or give feedback on the current status of a command if it takes a while to run. Another thing that strings are useful for is command prompts. Because AutoCAD is still primarily command-prompt based, you will surely be asking the user of your custom programs to provide information at the command line.

Table 3-5 shows some of the different string manipulation functions that are available in AutoLISP.

Table 3-5

Some of the Basic String Manipulation Functions

Function Syntax

Description

Result

 

 

 

(strcase string

Returns the string in either uppercase or

“HELLO”

[flag])

lowercase. If the optional flag value is set

 

 

to T, the string is returned in lowercase.

 

 

Example:

 

 

(strcase “Hello”)

 

 

 

 

(strcat

Concatenates all the supplied strings

“Hello

[string . . .])

together and returns a single string.

World”

 

Example:

 

 

(strcat “Hello”“ “ “World”)

 

 

 

 

(substr string

Returns a portion of the string based on the

“World”

start [length])

start position and the length supplied.

 

Example:

(substr “Hello World” 7)

(vl-string-subst replace_string pattern string [start])

Looks for the pattern in the string and

“Hello

replaces it with the replace_string

Planet”

value, and returns the result of the replace.

 

Example:

 

(vl-string-subst “Planet”

 

“World” “Hello World”)

 

List functions

Lists are everywhere in AutoLISP: You’ve been working with lists and weren’t even aware of it. Lists are used to represent groups of things. Up until this point, every line you have added to the MyStuff.LSP file has been a list with a function and arguments. Lists are used to represent things like coordinates or even how you work with entity properties.

More Than Just the Essentials of AutoLISP 697

Table 3-6 shows some of the different list functions that are available in AutoLISP.

Table 3-6

Some of the Basic List Functions

 

Function Syntax

Description

Result

 

 

 

(list

Returns a list of all the provided

(1.3 12.75 0)

[expression . . .])

expressions.

 

 

Example:

 

 

 

(list 1.3 12.75 0)

 

 

 

 

(car list)

Returns the first item in a list. There

1.3

 

are combinations of car and cdr

 

 

to get items in other places of the

 

 

list, such as cadr.

 

 

Example:

 

 

 

(car (list 1.3 12.75 0))

 

 

 

 

(cdr list)

Returns all items in a list except the

(12.75 0)

 

first one. There are combinations of

 

 

car and cdr to get items in other

 

 

places of the list, such as cadr.

 

 

Example:

 

 

 

(cdr (list 1.3 12.75 0))

 

 

 

 

(nth index list)

Returns the item in the location of

0

 

the list specified by the value of index.

 

 

The first item in the list is index 0.

 

 

Example:

 

 

 

(nth 2 (list 1.3 12.75 0))

 

 

 

 

(reverse list)

Reverses the item order of the list

(0 12.75 1.3)

 

and returns the new list.

 

 

Example:

 

 

 

(reverse (list 1.3

 

 

12.75

0))

 

 

 

 

 

Data conversion functions

As you start using more AutoLISP functions, you will want to use the results of one AutoLISP function with another, but each AutoLISP function requires you to use specific data types for its parameters. In these situations, you need to convert data from one data type to another. AutoLISP contains some functions specifically for this purpose.

Table 3-7 shows some of the different conversion functions that are available in AutoLISP.

Book X

Chapter 3

AutoLISP

Introducing

698 More Than Just the Essentials of AutoLISP

Table 3-7

 

Some of the Basic Conversion Functions

Function Syntax

Description

Result

 

 

 

(atof string)

Returns the string as a real number.

12.5

 

Example:

 

 

(atof “12.5”)

 

 

 

 

(atoi string)

Returns the string as an integer.

1.75

 

Example:

 

 

(atoi “1.75”)

 

 

 

 

(itoa int)

Returns the integer as a string.

“12”

 

Example:

 

 

(itoa 12)

 

 

 

 

(rtos number

Returns the real number into a formatted

“2.50000000”

[mode

string. Mode is a value of 1 – 5 and precision

 

[precision]]) is 0 through 8, the same as LUPREC.

 

 

Mode:

 

 

1

– Scientific

 

 

2

– Decimal

 

 

3

– Engineering

 

 

4

– Architectural

 

 

5

– Fraction

 

Example:

(rtos 2.5 2 8)

Saving and accessing values for later

Now that you have all these different values being returned by math, string, list, and conversion functions, it sure would be nice to save the values for use later in your custom programs. AutoLISP offers some different ways to store and retrieve values. Some of the ways affect how AutoCAD features behave or can be used to temporarily store information that can be recalled later in your program, such as a calculation or user input that might be needed for another function.

Table 3-8 shows some of the different data storage and retrieval functions that are available in AutoLISP.

Table 3-8

Data Storage and Retrieval Functions

 

Function Syntax

Description

Result

 

 

 

(setq variable

Sets the value to a variable. The variables

“Error

value [variable

only exist while the drawing is open.

occurred”

value] ...)

Example:

 

 

(setq msg “Error occurred”)

 

 

 

 

More Than Just the Essentials of AutoLISP 699

Function Syntax

Description

Result

(setvar variable_

Sets the value to a system variable.

“0”

name value)

Example:

 

 

(setvar “clayer” “0”)

 

 

 

 

(gertvar

Returns the current value of a system

“0”

variable_name)

variable.

 

 

Example:

 

 

(getvar “clayer”)

 

 

 

 

Exchanging information with AutoCAD

One of the pain points of drafting is initially setting up CAD standards and then trying to manage them. In this procedure, you create a custom command that draws a circle on a specific layer and sets it to a specified diameter:

1.From the Tools menu in AutoCAD, choose AutoLISP Visual LISP Editor.

AutoCAD launches the Visual LISP Editor.

2.From the Files menu in the Visual LISP Editor, choose Open File.

The Open File to Edit/View dialog box is displayed, allowing you to open an existing file.

3.In the Open File to Edit/View dialog box, browse to the My Documents folder and select the file MyStuff.LSP.

4.Click Open.

The contents of the MyStuff.LSP are loaded into a Text window.

5.In the Text window, place the cursor behind the last parenthesis and press Enter twice so there is a blank line below the ZW command.

6.In the Text window, enter the following expressions and command:

;;Custom command to create a new layer and draw a

;;0.5 diameter circle.

(defun c:BCIRC ( / cur-layer) ;; Store the current layer

(setq cur-layer (getvar “clayer”))

;;Create a new layer called Hole and set it current (command “.layer” “m” “Hole” “c” “5” “” “”)

;;Draw a 0.5 diameter circle and ask the user for

;;the center point

(command “.circle” PAUSE “d” 0.5)

Book X

Chapter 3

AutoLISP

Introducing

;; Restore the original layer

700 More Than Just the Essentials of AutoLISP

(setvar “clayer” cur-layer)

;; Stop an return values from being echoed (princ)

)

7.From the Files menu in the Visual LISP Editor, choose Save.

The new command is saved out of the MyStuff.LSP file.

8.From the Tools menu in the Visual LISP Editor, choose Load Text in Editor.

The custom command is loaded into AutoCAD and should now be ready to use.

9.Switch back to AutoCAD.

Focus should now be shifted to the AutoCAD application window.

10.At the command line, type BCIRC.

You should be prompted for the center point of the circle. A new circle object should be generated on the layer Hole, which is blue. The circle that is created should have a diameter of 0.5. The program should restore the previous layer before the CIRCLE command was started. If the user presses the Escape key, the previous layer won’t be restored. To resolve this, modify the command to look like the following code:

;;Custom command to create a new layer and draw a

;;0.5 diameter circle.

(defun c:BCIRC ( / cur-layer) ;; Store the current layer

(setq cur-layer (getvar “clayer”))

;;Create a new layer called Hole and set it current

(command “.layer” “m” “Hole” “c” “5” “” “s” curlayer “”)

;;Draw a 0.5 diameter circle and ask the user for

;;the center point

(command “.circle” PAUSE “d” 0.5)

;;Change the layer of the new circle (command “.change” “l” “” “p” “la” “Hole” “”)

;;Stop an return values from being echoed (princ)

)

With the revised code, the layer is never changed; instead, the object’s properties are modified with the CHANGE command. Although the second solution requires more code, it is much better because the drawing properties are never changed. If the user presses the Escape key, it won’t affect the current layer.

Getting Information to and from the User 701

Getting Information to and from the User

User input comes in a variety of different ways in AutoCAD. Typical user input in AutoCAD is done through the command line and with the pointing device. AutoLISP is full of different functions for collecting user input.

Table 3-9 shows some of the different user input functions that are available in AutoLISP.

Table 3-9

Some of the Basic User Input Functions

Function Syntax

Description

Result

 

 

 

(getpoint [point]

Requests the user to enter a point or

(21.9975

[message])

select one in a drawing.

13.1977 0.0)

 

Example:

 

 

(getpoint “\nPick first

 

 

point: “)

 

 

 

 

(getcorner point

Requests the user to enter a point or

(24.4237

[message])

select one in a drawing for the opposite

14.9183 0.0)

 

corner of a rectangle.

 

 

Example:

 

 

(getpoint ‘(0 0) “\nPick

 

 

opposite corner: “)

 

 

 

 

(getdist [point]

Requests the user to pick up to two

7.93347

[message])

points to calculate the overall distance

 

 

between the two points.

 

 

Example:

 

 

(getdist “\nPick two

 

 

points: “)

 

 

 

 

(getint

Requests the user to enter a

29

[message])

whole number.

 

 

Example:

 

 

(getint “\nEnter your

 

 

age: “)

 

 

 

 

(getreal

Requests the user to enter any number

32.6

[message])

with or without decimal places.

 

Example:

(getreal “\nEnter a number: “)

Giving feedback to the user

Book X

Chapter 3

AutoLISP

Introducing

Programming is all about giving and taking, so you should make sure that you are not just taking input from your users and not giving them feedback.