Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Книги_AutoCad_2 / AutoCAD 2006 and AutoCAD LT 2006 Bible_2004г__.pdf
Скачиваний:
142
Добавлен:
09.04.2015
Размер:
17.83 Mб
Скачать

Exploring

AutoLISP Further

AutoLISP offers many features that enable you to create sophisticated programs. These include variables, functions, and

conditional structures. You can use these features to easily work with drawing coordinates. You can retrieve information about drawing objects and then modify them. As a result, getting input from the user makes your programs more interactive.

AutoCAD LT does not support AutoLISP. This entire chapter is for AutoCAD only.

Creating Variables

You can’t do anything very useful in programming without using variables. A variable is a symbolic name that can be operated on in a given program. An important part of the usefulness of variables is that you can assign values to them.

The following example sets the value of 3 to a variable named radius.

(setq radius 3) 3

You can try this example out in Visual LISP in the Console window. If you want to use this variable on the AutoCAD command line, precede it with an exclamation point (!). For example:

Command: !radius 3

The exclamation point before a variable evaluates the value that is stored in the variable and returns it to the command line. When you use a variable in the Console window that you’ve already set, you don’t need the exclamation point. The Console treats everything that you type there as an AutoLISP expression.

Assigning strings to a variable is as easy as assigning numerals to a variable:

(setq name “Robin”) “Robin”

35C H A P T E R

In This Chapter

Creating variables and functions

Working with AutoCAD commands and system variables

Working with lists

Setting conditions and creating loops

Managing drawing objects

Getting input from the user

1052 Part VII Programming AutoCAD

You can also nest AutoLISP expressions by placing one expression inside the other.

(setq radius (+ 2 1)) 3

As explained in the previous chapter, AutoLISP evaluates LISP expressions from the innermost set of parentheses outward. In the above example, AutoLISP evaluates (+ 2 1) first, and then assigns the result to the variable radius.

STEPS: Using AutoLISP Variables from within AutoCAD

1.Open a drawing using the acad.dwt template.

2.Type (setq radius (+ 2 1)) . AutoLISP returns 3.

3.Start the CIRCLE command. Specify any center point. At the Specify radius of circle or [Diameter]: prompt, type !radius . AutoCAD draws a circle with a radius of 3 units.

4.Type (setq color “green”) . AutoLISP returns “green”.

5.Type -color . At the Enter default object color [Truecolor/Colorbook] <BYLAYER>: prompt, type !color .

6.Draw a circle. The circle is green because the current color is now green.

7.Save your drawing in your AutoCAD Bible folder as ab35-01.dwg.

Working with AutoCAD Commands

Accessing AutoCAD commands from within AutoLISP is a powerful way to automate commonly used functions. By combining access to commands from AutoLISP with variables as described in the previous section, you gain a great deal of flexibility.

Accessing AutoCAD commands

In the previous chapter, when you looked at an AutoLISP routine (see Figure 34-4), you saw an example of the COMMAND function. You use the COMMAND function in AutoLISP to execute AutoCAD commands. This function treats all subsequent operands as if they were typed at the command line interactively. When programming COMMAND functions in AutoLISP, exactly duplicate what you would do at the command line. For example, to draw a line, you follow the steps shown in the following table. The second column shows how you would perform the same action in an AutoLISP routine.

Enter line at the command line

“line” (or “_line”)

Specify the start point for the line

Use a variable, actual coordinates, or pause

 

for user input.

Specify the endpoint

Use a variable, actual coordinates, or pause

 

for user input.

Press Enter to end the LINE command

Use an empty set of two quotation marks to

 

represent pressing Enter either within a

 

command or to end a command.

For example, if you’re using the variables startpt and endpt for the start point and endpoint of a line, here’s how you would access the LINE command in an AutoLISP expression:

(command “_line” startpt endpt “”)

Chapter 35 Exploring AutoLISP Further 1053

Creating functions

Functions always begin with the operator DEFUN. You can define three principal types of functions:

The type that you have been using thus far precedes the command name defined by DEFUN with c:, which is interpreted by AutoCAD as a command and enables you to use the function by name at the AutoCAD command line. The function becomes usable like any other AutoCAD command.

You can also create a function definition without preceding the name with c:. This type is most valuable when it’s called by other AutoLISP operations. If you need to execute it at the command line, you must enclose the function name in parentheses. Similarly, you can execute functions prefixed with a c: as an AutoLISP expression by enclosing the functions in parentheses, as in (c:circle3).

The third type is S::STARTUP. By defining a function (usually in acaddoc.lsp, which is loaded into every drawing) with the name S::STARTUP, every AutoLISP function in the routine will automatically execute after the drawing has fully initialized. The reason for the S::STARTUP function is to ensure that AutoLISP routines that use the COMMAND function run only after AutoCAD fully initializes the components that can execute commands.

When you create an S::STARTUP function, you need to decide where to put it. Chapter 34 briefly explained the difference between acad.lsp and acaddoc.lsp. The need for two files arose because AutoCAD includes MDI, which enables you to open more than one drawing at a time. For more information, see the “Automatically Loading LSP Files” sidebar. S::STARTUP is a great tool for enhancing productivity. In this way, you can automate whatever general setup operations you normally do at the beginning of a drawing session, or for every drawing that you open.

Automatically Loading LSP Files

AutoCAD automatically loads four AutoLISP files. Two files, acad2006.lsp and acad2006doc.lsp, are specific to AutoCAD 2006. Autodesk recommends that you reserve these files for AutoCAD use. The acad2006.lsp file is loaded only once per AutoCAD session when you first load AutoCAD, while the acad2006doc.lsp file is loaded in the initial session, and then each time a drawing is opened.

The other two automatically loaded AutoLISP files are reserved for you, the user. These files are acad.lsp, which is loaded once per AutoCAD session, and acaddoc.lsp, which is loaded every time a drawing is opened. What this means to you is that you can place different initialization routines in each file — one for AutoCAD initialization (acad.lsp), and the other for the initial drawing as well as future drawings. You can place an S::STARTUP function in both acad.lsp and acaddoc.lsp. However, be aware that placing different S::STARTUP functions in both files effectively disables the S::STARTUP function defined in acad.lsp.

You must create both acad.lsp and acaddoc.lsp. However, after you create any AutoLISP routine and save it under either name, you can add additional routines to the same file. AutoCAD automatically loads these files, as long as they exist.

The load order of these initialization files is:

1.acad2006.lsp: Loaded by AutoCAD 2006

2.acad.lsp: User-defined initialization file loaded once, upon loading AutoCAD 2006

Continued

1054 Part VII Programming AutoCAD

Continued

3.acad2006doc.lsp: Document-level initialization file loaded by AutoCAD 2006

4.acaddoc.lsp: User-defined document-level initialization file

Here’s an AutoLISP routine that uses both the DEFUN and COMMAND functions:

(defun c:redline (/ startpt endpt) (terpri)

(setq startpt (getpoint “Select the redline start point:”)) (terpri)

(setq endpt (getpoint “Select the redline end point:”)) (command “_line” startpt endpt “”)

(command “_chprop” “_last” “” “_color” “red” “”)

)

Here’s an explanation of this routine:

The first line of this routine defines a function called redline. Because redline is preceded by c:, you can type redline at the command line when using it within AutoCAD. As you may remember from the discussion of the circle3 routine, the expression (/ startpt endpt) means that redline has two local variables that are available only to this routine. These variables are used in the next two lines.

The new instruction, terpri, on the second and fourth lines, tells AutoCAD to print a blank line at the command line. You can use this instruction to improve readability of the prompts. Otherwise, two or more prompts run together on one line.

Reading the third line from the innermost parenthesis pair outward, AutoCAD obtains the red line’s start point from the user with the prompt Select the redline start point: and sets the variable startpt equal to that start point’s value. Similarly, the fifth line obtains the red line’s endpoint and sets the variable endpt to that value.

Line 6 uses the AutoLISP COMMAND function. It issues the LINE command, specifies the start point and endpoint, and uses a set of empty quotation marks to replicate pressing Enter to end the LINE command.

Line 7 uses the same syntax for the CHPROP command. It does the following: issues the CHPROP command; selects the line that you just used by using the Last Selection option; ends object selection by using the empty set of quotation marks; specifies the Color option; and sets the color to red. Another empty set of quotation marks ends the command.

Line 8 ends the redline routine with a closing parenthesis.

To use this routine, you would follow these steps:

1.Open Visual LISP and start a new file.

2.Type the routine.

3.Save the routine as redline.lsp and place it in AutoCAD’s Support folder or any other folder that you may have created for AutoLISP routines, and added to AutoCAD’s support file search path.

Chapter 35 Exploring AutoLISP Further 1055

On the

CD-ROM

4.Load the routine.

5.Switch to AutoCAD.

6.At the command prompt, type redline .

7.In response to the prompts for the start point and endpoint of the redline, choose any two points on-screen. AutoCAD draws a red line between the two selected points.

The file redline.lsp is in the \Results folder on the CD-ROM. Feel free to copy it to your system and play around with it. For example, using your knowledge of the circle3 routine discussed in Chapter 34, you could create a red circle.

Here is another example of an AutoLISP routine that creates an S::STARTUP function. It uses several of the features that I’ve been discussing in this chapter.

(defun s::startup ()

(command “_rectang” “_width” “0.1” “0,0” “10,10”) (command “_text” “8,1” “0.2” “0” “name”)

(command “_text” “8,0.7” “0.2” “0” “date”) (command “_text” “8,0.4” “0.2” “0” “revision”) (command “_zoom” “_extents”)

)

This routine creates a simple title block and border each time you open a new drawing, as shown in Figure 35-1.

Figure 35-1: The result of the S::STARTUP routine.

In order to use this routine — or one of your own — you can add it to the end of acaddoc.lsp. AutoCAD 2006 does not come with this file, and so the first time that you want to use it, you must create it.

Caution

Before using the S::STARTUP function, be sure that an S::STARTUP function does not already exist

 

in the file. Other applications that you may have purchased or downloaded may include an

 

S::STARTUP file. Adding a second S::STARTUP could possibly interfere with the operation of these

 

other applications. In Notepad, choose Search Find and type s::startup in the Find What

1056 Part VII Programming AutoCAD

text box. Click Find Next. If an S::STARTUP routine already exists, then add the body of your S::STARTUP function (minus the first line, which already exists) to the end of the existing S::STARTUP routine and save the file.

Creating functions with arguments

You can create functions that accept arguments, sometimes called parameters. An argument is a value that must be supplied with the function. The function then uses the value of that argument in its operation.

Earlier in this chapter, I explained that local variables are placed in parentheses after a slash. Arguments go in the same set of parentheses, but before the slash. If there are no local variables, you don’t need the slash. Here is an example of a function with one argument:

(defun chg2red (selected_object)

...

)

To actually use this routine in AutoCAD or within another AutoLISP routine, use the format (chg2red selected_object). The argument is sent to the chg2red routine by adding the argument after the function name, all enclosed in parentheses.

Whenever you use the chg2red function within a routine, you must follow it by its argument. You can obtain the argument by using a variable whose value you’ve set in the routine, by obtaining a value through user input, or by typing in a specific value when you use the function.

The following exercise uses a function that is called from within the routine.

On the

The file used in the following exercise on using AutoLISP functions and commands, ab35-

CD-ROM

a.lsp, is in the Drawings folder on the CD-ROM. If you haven’t already done so, place the

 

CD-ROM in your CD-ROM drive.

STEPS: Using AutoLISP Functions and Commands

1.Start a new drawing using any template.

2.Use Windows Explorer to copy ab35-a.lsp from the CD-ROM to AutoCAD’s Support folder, or any folder that you’ve created for AutoLISP routines and added to AutoCAD’s support file search path. This file is shown in Figure 35-2.

Figure 35-2: An AutoLISP routine to change an object’s color to red.

3.Choose Tools AutoLISP Visual LISP Editor. In Visual LISP, open ab35-a.lsp. The routine appears in the Edit window.

4.Choose Load Active Edit Window.

5.Choose Activate AutoCAD.

Chapter 35 Exploring AutoLISP Further 1057

6.Draw any object.

7.At the command line, type chgcolor .

8.At the Select an object to change to red: prompt, select the object that you drew in Step 6. Watch its color change to red.

Don’t save the routine or your drawing.

Here’s how the routine works:

This routine defines a function, chg2red, which is not preceded by c:. It has one argument, selected_object.

What AutoLISP actually ran when you typed chgcolor in Step 7 is the function c: chgcolor on the fourth line of the routine. In the last AutoLISP statement in that function — (chg2red selected) — the variable selected is derived from the previous step as a result of the operation entsel (entity select).

The variable selected is the argument passed to the function chg2red. The function chg2red now knows what object to operate on.

The function chg2red then uses the CHPROP command to change the object’s color to red.

Note To actually call this function at the command line, you would need to type (chg2red arg) where arg is an argument (in this case, it must be an entity name). Entity names are discussed later in this chapter.

Working with system variables

AutoCAD has a wide variety of system variables to control the drawing environment. Thankfully, the creators of AutoLISP enabled the AutoLISP programmer to automate setting and to retrieve AutoCAD system variables.

Don’t confuse the terms variable and system variable. A variable is a value that is stored for use in a routine. A system variable is an AutoCAD setting that changes how AutoCAD works.

To set or retrieve AutoCAD system variables, you use two operators, SETVAR and GETVAR, which can be used on AutoCAD system variables. (You can use SETVAR only on system variables that are not read-only.) Here’s how they work:

SETVAR stands for set variable. You use SETVAR to change a system variable. Place the system variable in quotes, followed by the new value, as in (setvar “cmdecho” 0).

GETVAR stands for get variable. It enables you to obtain the value of any system variable. As soon as you have the value, you can set it to a variable. This is often done so that you can return a system variable to its previous value if you’ve changed it during a routine. Place the system variable in quotes after using GETVAR, as in (getvar “cmdecho”).

Although you can use SETVAR and GETVAR on many system variables, here are two system variables that are often changed in an AutoLISP routine:

In all of the AutoLISP routines created thus far, AutoCAD’s command responses could be seen scrolling off the command-line window. The CMDECHO system variable determines whether you see prompts and input during the functioning of AutoLISP’s COMMAND function. By default, echoing is on (set to 1). If you set it to 0, you do not see prompts and input, and the functioning of the AutoLISP routine looks cleaner and runs slightly faster.

1058 Part VII Programming AutoCAD

On the

CD-ROM

The FILEDIA system variable turns on and off the display of dialog boxes that enable you to choose files. Turning off this system variable enables you to work with files on the command line in AutoLISP routines.

The file used in the following exercise on using AutoLISP to work with system variables, ab35-a.lsp, is in the Drawings folder on the CD-ROM.

STEPS: Using AutoLISP to Work with System Variables

1.If you did the previous exercise and copied ab35-a.lsp to AutoCAD’s Support folder (or another folder that you created for AutoLISP routines, and added to AutoCAD’s support file search path), open it from that folder. If you did not do the previous exercise, copy ab35-a.lsp from the CD-ROM to AutoCAD’s Support folder, or another folder in AutoCAD’s support file search path.

2.Open a new drawing using the acad.dwt template. Choose Tools AutoLISP Visual LISP Editor to open Visual LISP. Click Open and open ab35-a.lsp. Edit it to read as follows:

(defun chg2red (selected_object)

(command “_chprop” selected_object “” “_color” “red” “”)

)

(defun c:chgcolor (/ selected old_cmdecho) (setq old_cmdecho (getvar “cmdecho”)) (setvar “cmdecho” 0)

(terpri)

(setq selected (entsel “Select an object to change to red:”)) (chg2red selected)

(setvar “cmdecho” old_cmdecho)

)

3.Save the file as ab35-01.lsp in the same location.

4.Choose Load Active Edit Window to load the routine.

5.Draw any object.

6.At the command line, type chgcolor .

7.At the Select an object to change to red: prompt, select the object that you drew in Step 5. You no longer see the prompts scrolling by. The object that you select turns red, and AutoCAD immediately displays the command prompt.

Don’t save your drawing.

Here’s how this routine works. This discussion assumes that you have already read the discussion of the previous routine, which was very similar.

First, you added a new variable, old_cmdecho, to the chgcolor function.

In the following line, you set this variable to the current value of the CMDECHO system variable. You obtained this current value using GETVAR.

You then used SETVAR to set the AutoCAD system variable CMDECHO to 0.

You may need to see the commands echoed for debugging purposes, and so it would prove best to return CMDECHO to the value that it was set to before running the routine.

Соседние файлы в папке Книги_AutoCad_2