AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® -...

27
AutoLISP® / Visual LISP® - Part 1 Robert Green - CAD-Manager.com AutoLISP/Visual LISP is a powerful way to extend AutoCAD® functionality and make you more productive, but many avoid using it because they think it’s too hard to learn. Not so! This course starts at the beginning by defining key files then moves rapidly through basic syntax including points, lists, accessing the command line, storing and retrieving variables, writing your own command functions, defining/undefining commands, data types, logical functions IF and NOT, working with simple sets and controlling the AutoCAD start-up so all your functions load automatically. To make it all easy to understand, we’ll use some real world examples and even give you some homework projects you can work on after class to extend your learning. If you want to tap the power of AutoLISP and increase your productivity, fasten your seat belt for this session. About the Speaker: Robert is head of the Robert Green Consulting Group and a 14-year veteran speaker at Autodesk University. You've likely read his work in Cadalyst magazine, where he authors the "CAD Manager" column, or in his bi-monthly CAD Manager's Newsletter. He holds a degree in Mechanical Engineering from the Georgia Institute of Technology and gained his CAD skills from 23 years of AutoCAD®, MicroStation®, and MCAD® software usage. Since starting his own company in 1991, Robert has performed consulting and teaching duties for private clients, and throughout the U.S. and Canada. [email protected]

Transcript of AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® -...

Page 1: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

AutoLISP® / Visual LISP® - Part 1 Robert Green - CAD-Manager.com

AutoLISP/Visual LISP is a powerful way to extend AutoCAD® functionality and make you more productive, but many avoid using it because they think it’s too hard to learn. Not so! This course starts at the beginning by defining key files then moves rapidly through basic syntax including points, lists, accessing the command line, storing and retrieving variables, writing your own command functions, defining/undefining commands, data types, logical functions IF and NOT, working with simple sets and controlling the AutoCAD start-up so all your functions load automatically. To make it all easy to understand, we’ll use some real world examples and even give you some homework projects you can work on after class to extend your learning. If you want to tap the power of AutoLISP and increase your productivity, fasten your seat belt for this session.

About the Speaker:

Robert is head of the Robert Green Consulting Group and a 14-year veteran speaker at Autodesk University. You've likely read his work in Cadalyst magazine, where he authors the "CAD Manager" column, or in his bi-monthly CAD Manager's Newsletter. He holds a degree in Mechanical Engineering from the Georgia Institute of Technology and gained his CAD skills from 23 years of AutoCAD®, MicroStation®, and MCAD® software usage. Since starting his own company in 1991, Robert has performed consulting and teaching duties for private clients, and throughout the U.S. and Canada.

[email protected]

Page 2: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

2

Origins and expectations

AutoLISP is a descendant of Common Lisp, which is actually a very old programming language that was conceptualized for artificial intelligence applications. It also happened to be open source and was therefore an ideal (and cost-free) way for AutoCAD to be extended with a programming language. Since AutoLISP doesn’t have to be compiled, meaning you can run programs directly, it was even more ideal as almost nobody but hard-core coders even knew what a program compiler was in the mid-1980’s.

AutoLISP is a very powerful language that can take years to learn and master. I’ve been working with it since 1990 and I still learn new things about AutoLISP on every project. Having said this, I’d like to say that there is a lot you can do with AutoLISP without having to be a programming jock if you approach things with a cookbook-style approach and use existing routines.

Key files, functions and variables

The first thing to understand is that AutoLISP has some key files and a key function that perform startup operations for you. The key files can contain custom AutoLISP code that you want loaded whenever AutoCAD starts up. There are also a few useful functions that AutoLISP has predefined to perform startup operations for you. I’ll summarize everything here:

ACAD200?.LSP Names like ACAD2005.LSP, ACAD2006.LSP, ACAD2008.LSP, ACAD2010.LSP, etc. This file loads first when AutoCAD starts up.

ACAD.LSP This file loads second when AutoCAD starts up.

ACAD200?DOC.LSP Names like ACAD2005DOC.LSP, ACAD2006DOC.LSP, ACAD2007DOC.LSP, ACAD2008DOC.LSP, ACAD2009DOC.LSP, etc. This file loads third when AutoCAD starts up.

ACADDOC.LSP This file loads fourth when AutoCAD starts up.

MENUNAME.MNL This file loads after the previous files but only when its CUI menu counterpart (either a CUI or CUIX) is loaded into AutoCAD. By placing AutoLISP code in this file you can be assured that the code will be loaded into memory ONLY when the parent menu is in use.

ACADLSPASDOC This variable controls the loading of ACAD.LSP. ACAD.LSP file only loads once unless you set the variable ACADLSPASDOC to 1 rather than the default setting of 0.

Page 3: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

3

EXERCISE: Key Files, Functions and Variables

To verify that you can create an AutoLISP file that loads and executes, follow these steps:

• Open a text editor like Notepad • Type in the following line in the Notepad session taking great care to match all the

parentheses and quotes as I have

(prompt “The ACADDOC.LSP file has loaded.”)

• Now save the file with the name ACADDOC.LSP and place the file in the SUPPORT folder of your AutoCAD application software. Typical locations would be as follows depending on your AutoCAD version:

C:\Program Files\AutoCAD 2006\Support C:\Program Files\AutoCAD 2007\Support C:\Program Files\AutoCAD 2008\Support

• Start AutoCAD and check your command prompt history (use the F2 key) to be sure the message “The ACADDOC.LSP file has loaded” shows up.

• • Start multiple drawing sessions in the same session of AutoCAD and verify that the

same message is displayed at the command prompt history as each drawing starts.

Recommendation

The above methodology is recommended for adding basic AutoLISP syntax to your AutoCAD environment. By using the ACADDOC.LSP methodology you don’t have to worry about the ACADLSPASDOC setting and since the file probably doesn’t exist in your installation already, there’s essentially zero chance you’ll write over or destroy any existing customization.

Note 1: Using ACADDOC.LSP in the SUPPORT directory yields maximum results, low complexity and far less chance of messing something up.

Note 2: Be sure to use a plain text editor like Notepad rather than a word processing program like Word. Notepad will strip out weird characters like backward quote marks that can cause your program to malfunction.

Page 4: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

4

Syntax basics So now that you know which files to put your AutoLISP code in, let’s establish the basics of AutoLISP syntax so you can start writing some code. The basic topics you need to understand are:

• Lists and arguments • Rules of AutoLISP • Variables • Functions • Accessing the command line • Special characters • User input

We’ll examine these topics using a combination of lecture and viewing code examples. Please understand that given our time constraints I can’t fully develop all the theory behind these commands. I’ll have to ask you to trust me for the meantime, then research the language more thoroughly later when you have a working knowledge of the language. Let’s get started!

Lists and arguments

Anything you do in AutoLISP is formatted as a list. Lists can have both ARGUMENTS and FUNCTIONS embedded within them so you can perform various activities. Here are a few examples:

(+ 20 30) Here + is the FUNCTION and the two numbers are ARGUMENTS

(command “line” “0,0” “1,1” “”) Here COMMAND is the function, all others are ARGUMENTS

If you study more you’ll start to see that any AutoCAD entity can be described as a complex list like this:

((-1 . <Entity name: 400b1580>) (0 . "LINE") (330 . <Entity name: 40094cf8>) (5 . "378") (100 . "AcDbEntity") (67 . 0) (410 . "Model") (8 . "2") (100 . "AcDbLine") (10 198.441 78.786 0.0) (11 247.87 179.589 0.0) (210 0.0 0.0 1.0))

Though it isn’t obvious, this list describes a line that is drawn on layer “2” with a start point and end point and a UCS vector of 0,0,1. Once you start to read lists, you’re on your way!

Lists are simply a way to group information or to submit information, in the form of ARGUMENTS to a FUNCTION as we illustrated above. The AutoCAD entity lists allow you to

Page 5: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

5

perform actions on AutoCAD entities via more advanced programming techniques than we’ll look at today. I just want you to have a glimpse of what’s under AutoCAD’s hood.

Rules of AutoLISP

“For every ( there is an equal and opposite )” – Einstein circa 1939

Like this: (setq A 3.0)

Not like this: (setq A 3.0)) or (setq A 3.0

Same goes for quote marks!

Like this: (setq name “Robert Green”)

Not like this: (setq name “Robert Green) or (setq name Robert Green”)

When formatting numbers always avoid “invalid dotted pairs.”

Like this: (setq A 0.5)

Not like this: (setq A .5)

Arithmetic functions a little different than you’re used to. For example:

Standard language AutoLISP equivalent Result

8 + 4 (+ 8 4) 12

8 + 2.3 (+ 8 2.3) 12.3

5.0 ÷ 4.0 (/ 5.0 4.0) S1.25

5 ÷ 4.0 (/ 5 4.0) 1.25

5.0 ÷ 4 (/ 5.0 4) 1.25

5 ÷ 4 (/ 5 4) 1 (Why? Integers!)

Page 6: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

6

More complex math gets a little persnickety. Look at the following examples and remember that AutoLISP works from the inside out with respect to parentheses. For example:

Standard language AutoLISP equivalent Result

(8 + 4) * 3 (* (+ 8 4) 3) 36

(3.0 * 5.0) ÷ 4.0 (/ (* 3.0 5.0) 4.0) 3.75

((4 + 4) * 3) ÷ 2 (/ (* (+ 4 4) 3) 2) 12

I’ll talk more about data types in an upcoming session but for now take careful note that how you enter numbers (real or integer) has everything to do with how the numbers get processed.

Accessing the command line To make AutoCAD and AutoLISP shake hands, the most basic skill set you’ll need is accessing the command line. I alluded to the idea of a COMMAND function with arguments in the previous section but I didn’t do any real practical examples. Let’s have a look at several possible examples of “talking” to AutoCAD via the AutoLISP command line interface.

If you wanted to draw a line between two user-supplied points on the screen, you’d do the following:

Type in LINE to start the line command

Click POINT for first point location

Click POINT for second point location

Type in ENTER to halt the command

In AutoLISP you’d do it this way:

(command “line” pause pause “”)

Note: The PAUSE instruction waits for the user and the “” is equal to hitting the ENTER key. Why? Because that’s the way the good folks at Autodesk set it up!

How about a few more examples of command line access that you may want to actually use? Here are a few examples:

Page 7: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

7

AutoLISP function Purpose _

(command “viewres” “y” “5000”) Sets view resolution for no jaggy circles

(command “-color” “BYLAYER”) Sets color to BYLAYER

(command “-linetype” “set” “BYLAYER” “”) Sets linetype to BYLAYER

(command “menu” “menuname.mnc”) Loads menu file of your choosing

Now let’s look at an example with user input:

AutoLISP function Purpose _

(command “viewres” “y” pause) Sets view resolution to a user value

Variables

While knowing about lists is one thing, doing something functional with lists depends on being able to store and pass variables within lists.

First things first: How do you store a variable? Let’s say you wanted to store a variable called VALUE that has the number 12.7 associated with it. In order to set the variable we need to use the SETQ function (think SET eQual) like this:

(setq VALUE 12.7)

This particular variable would be a REAL NUMBER variable. Some other variable types are shown here for your reference:

(setq VALUE 1) This would be an INTEGER variable

(setq VALUE “Happy”) This would be an STRING variable

(setq VALUE 1) This would be an INTEGER variable

Now when you interact with AutoCAD you have to pass the variable in the command line. Use this case as an example:

(setq VIEWRES_VALUE 5000)

(command “viewres” “y” viewres_value)

Page 8: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

8

What would happen in this case?

(setq VIEWRES_VALUE “Happy Birthday!”)

(command “viewres” “y” viewres_value)

This wouldn’t make much sense, would it? When you write a program you have to make sure that the variables you use match up with the AutoCAD commands the variables are “speaking” to. It makes sense to pass a numeric value to the VIEWRES command, but it doesn’t make any sense to send it a string-type variable. Understanding this simple trick of variable typing makes things a lot easier.

User input Let’s say you wanted to write a program that would create a wheel with some spokes in it. Well, how many spokes should the wheel have? If you write a program with a known number of spokes, say 8, the program could then draw wheels with 8 spokes. Wouldn’t it be better to write a program that draws wheels with a variable number of spokes? For that matter, how about writing a program where you specify the number of spokes and the diameter of the wheel?

In order to specify how many spokes are on the wheel and how big the diameter is, you’ll need to ask the user to define those variables like this:

(getdist “\nInput a distance: ”) Prompts the user for distance value

(getreal “\nInput a real number: ”) Prompts the user for real number value

(getint “\nInput an integer number: ”) Prompts the user for integer value

(getstring “\nInput text: ”) Prompts the user for string/character value

Now let’s associate the input the user gives us to a named variable like this:

(setq user_dist (getdist “\nInput a distance: ”))

(setq user_real (getreal “\nInput a real number: ”))

(setq user_int (getint “\nInput an integer number: ”))

(setq user_string (getstring “\nInput text: ”))

Or, to revisit our spoke/wheel analogy, how about this:

(setq wheel_dia (getdist “\nEnter wheel diameter: ”))

(setq spokes (getint “\nEnter number of spokes: ”))

Page 9: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

9

User command functions OK, we know how to collect information from the user and we know how to pass that input to AutoCAD’s command line. But how can we do all this in a way that adds to AutoCAD’s native set of commands? After all, wouldn’t it be ideal if we could write AutoLISP routines that would trick AutoCAD into thinking it had new commands? If we do a good enough job, our CAD users won’t even know we’ve programmed commands for them.

Let’s have a few simple examples so you can see how it works:

The idea: We want to create a ZA command that does a zoom all.

The code: (defun C:ZA ()

(command “.zoom” “a”)

(princ)

)

Here’s what the routine is doing on a line-by-line basis:

(defun C:ZA () Reserves a command called ZA with no inputs to the command which explains the () after the command name. Don’t worry about why the () works as it does now; to get more into this would require much more detailed coverage.

(command “.zoom” “a”) Engages the command line and passes the arguments .ZOOM and A for all to the command processor. Why the “.” in front of zoom, you ask? Because it guarantees that we’ll use the native ZOOM command instead of any other version that may be redefined. More on this later.

(princ) Clears the print console and suppresses AutoLISP from leaving a NIL result at the command line as the function terminates. Don’t worry about why it works, it just does and your program will look a lot cleaner for using it.

) Closes the function out. This actually balances the misbalanced paren count in the first line of the function. (You did notice the imbalance, right?)

Page 10: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

10

Here are a few more I like to use:

(defun C:VR ()

(command “viewres” “y” “5000”)

)

(defun C:BL ()

(command “-color” “BYLAYER”)

(command “-linetype” “set” “BYLAYER” “”)

(princ)

)

More user command functions Let’s look at some additional functions and try to figure out why they work and crank up the complexity just a little to keep things interesting. I’ll comment on the code in comment form (that is, the code includes a “;” character which allows us to write comments in our programming). Here goes:

The idea: We want to create an FZ command that performs a fillet command but makes sure that the radius is set to 0.0 so we fillet sharp corners.

(defun c:fz () ; Define an FZ command

(setvar “filletrad” 0.0) ; Set the fillet radius to 0.0 using SETVAR

(command “.fillet” pause pause) ; Invoke FILLET and wait for two user inputs

(princ) ; Clear the command line

)

We learned that we can set AutoCAD variables using the SETVAR function very easily. It turns out that you can set a variable using SETVAR and can read the value of any variable using, cleverly enough, GETVAR. Don’t know which variable you need? Look in the AutoCAD help file under the command topic SETVAR and you’ll find a list of all the variables and what they do!

Page 11: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

11

The program will work but it would be better if we checked the value of the fillet radius first and then made sure we put it back the way we found it when our program is done running. Here’s how:

(defun c:fz () ; Define an FZ command

(setq old_filletrad (getvar “filletrad”)) ; Store the old fillet radius value

(setvar “filletrad” 0.0) ; Set the fillet radius to 0.0 using SETVAR

(command “.fillet” pause pause) ; Invoke FILLET and wait for user inputs

(setvar “filletrad” old_filletrad) ; Put the fillet radius back

(princ) ; Clear the command line

)

This example illustrates reading a system variable value into an AutoLISP variable, then using that variable later in the program to AutoCAD’s fillet radius to its previous value. That’s it! Not so bad, really.

Auto Purge (ATP)

Here’s a function I like to use daily. It does an autopurge and save (thus combining two commands into one) by keying in ATP:

(defun c:atp ()

(command “-purge” “a” “*” “n” “.qsave”)

(princ)

)

Page 12: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

12

Closing things out - Cool stuff to know There are a few other little handy things to sprinkle into your AutoLISP sessions that I’ll cover here and comment on one by one:

Comment “;” Lines

You may have noted my use of the semi-colon character in some examples. The semi-colon is the comment character in AutoLISP which allows you to embed notes in the code. I find commenting very helpful because several months from now when I’m working on a program I won’t remember what I was doing way back when I wrote the program.

Anything that comes after the semi-colon is simply ignored until the next line of the program starts.

Dash “-“ Form Commands Why did I use –PURGE instead of just PURGE in the ATP example?

I used the dash form of the PURGE command specifically because I didn’t want the dialog form of the command invoking. While the dialog form of commands like PURGE and LAYER are cool for the user, an AutoLISP command can’t reach out and grab the mouse to interact with the command, right?

So if a command has a dialog box, like LAYER for example, just try putting a dash “-“ in front of the command and see if it works!

I prefer using the dash form of commands because I can always go to AutoCAD’s command prompt and type in the dash form of the command and see exactly how it will behave. I therefore make fewer mistakes writing my programs!

Extra credit: If you’re a glutton for punishment look in the AutoLISP function reference (find it under the AutoCAD help system) and look up the INITDIA function. This AutoLISP function provides a more detailed explanation of how dialogs are handled within AutoLISP functions.

Dot “.“ Form Commands

In my FILLET programming example, why did I type the command as “.FILLET” rather than just “FILLET”?

I used the dot form of the command just in case some enterprising CAD manager had undefined the FILLET command previously. The dot form of the command allows you to call the command even if has been undefined. We’ll talk more about undefining functions shortly.

Page 13: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

13

Alerting Users

You can send a message to the user like this: (alert “Message goes here”)

Note: The user must acknowledge the alert by clicking the OK button!

Undefining commands

You can turn AutoCAD commands off like this:

(command “.undefine” “LINE”)

(command “.undefine” “TORUS”)

This way, if you don’t want users messing with a command, you just shut it off. Place the code in your ACAD.LSP file and it’ll have the equivalent effect of disabling AutoCAD’s command vocabulary.

Undefining and alerting

You can undefine a command and alert the user like this:

(command “.undefine” “TORUS”)

(defun C:TORUS ()

(alert “I don’t want you using that command!”)

(princ)

)

Page 14: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

14

Redefine via AutoCAD

To bring a command back simply use the REDEFINE command at the AutoCAD command prompt like this:

Command: redefine

Enter command name: torus

Redefine via AutoLISP

Now take it another step and redefine the function with an alert to the user like this:

(command “.undefine” “TORUS”)

(defun C:TORUS ()

(alert “I don’t want you using that command!”)

(princ)

)

This way the user will get the message!

Controlling Command Echo

Many times you may have a program that invokes a command, yet you don’t want the user to see the command you’ve invoked. As an example, the BL function I wrote earlier could be made to run in STEALTH MODE by doing this:

(defun C:BL ()

(setvar “cmdecho” 0) ; Turns the echo off

(command “-color” “BYLAYER”)

(command “-linetype” “set” “BYLAYER” “”)

(setvar “cmdecho” 1) ; Turns the echo back on

(princ)

)

Page 15: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

15

Kicking It Up a Notch

Conditional operators It all starts with injecting logic into your programs so they can actually “be smart” via branching and looping structures. In programming parlance we call these types of functions conditional operators.

In order for your programs to execute logical operations you need to use conditional operators like IF, WHILE and COND depending on the particular circumstances.

The IF conditional

Let’s kick things off with the IF command.

Basic format: (IF (TEST EXPRESSION) (TRUE CASE) (FALSE CASE) )

As you can see the IF command evaluates a test to see if the test is TRUE or FALSE. The result of the IF command then goes two a true case and a false case. Therefore the IF command can be though of as a logical “fork in the road” since there are two distinct outcomes.

Pseudo code: A user is prompted for an integer variable called SPOKES If the variable has a value less than 20 then print “LESS THAN 20” If the variable has a value greater than/equal to 20 then print “MORE THAN 20”

Real code: (if (< spokes 20) (alert “LESS THAN 20”) ; true case (alert “MORE THAN 20”) ; false case )

The COND conditional

Page 16: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

16

COND is like a “super IF” command in that it allows you to evaluate a test case and take action but you may have any number of outcomes rather than the IF statements two outcomes. Let’s see the structure of the command:

Basic format: (COND

( (TEST EXPRESSION 1) (OUTCOME) )

( (TEST EXPRESSION 2) (OUTCOME) )

( (TEST EXPRESSION 3) (OUTCOME) )

)

Note that there are more parentheses to keep track of and that the structure is a little different than IF, but the basic premise is very much like IF.

Pseudo code: A user is prompted for an integer variable called SPOKES If the variable has a value less than 10 then print “SMALL WHEEL” to the screen If the variable is between 10 and 15 print “MEDIUM WHEEL” If the variable is greater than 15 print “LARGE WHEEL”

Real code: (setq spokes (getint “\nEnter number of spokes: “)) (cond

( (< spokes 10) (alert “SMALL WHEEL”) ) ( (and (>= spokes 10) (<= spokes 15)) (alert “MEDIUM WHEEL”) ) ( (> spokes 15) (alert “LARGE WHEEL”) )

) Note: See how the AND operator was used to evaluate a more complex test case? In the MEDIUM case the spokes had to be in the range between 10 and 15 so two evaluations were required.

The WHILE conditional The main use of the WHILE conditional is to execute a looping structure to qualify user inputs. Let’s see the structure of the command: Basic format: (OBTAIN VARIABLE)

(WHILE (TEST EXPRESSION ON VARIABLE)

Page 17: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

17

(Statement 1)

.

(Statement N)

)

Let’s say we want to prompt the user for a number of spokes but the number of spokes needs to be no less than 20 for our purposes. How can we handle a case where the user gives us an incorrect number? Let’s use the WHILE conditional like this:

(setq spokes 0) (while (< spokes 20) (setq spokes (getint “\nEnter number of spokes: “)) )

In this case we initialize the variable to less than 20 so we will enter the WHILE loop. Now if a user enters a value for spokes that is LESS than 20 they’ll be stuck in the loop. If they enter a value of 20 or higher the test expression is true and the loop is exited. Simple enough.

Conditional Example Let’s now write a program that uses conditional structures to achieve some complex logic. Here’s the pseudo code for the example:

• Prompt the user for a number of spokes • Be sure they give you at least 8 spokes but not more than 24 spokes • Write SMALL MEDIUM or LARGE to the screen based on the rules we used in the COND

example

Real Code First I’ll write the code that assures user input and enforces the maximum and minimum spokes cases. This looping structure will use a WHILE function along with a complex test case like this:

(setq spokes 0) (while (or (< spokes 8) (> spokes 24)) (setq spokes (getint “\nEnter number of spokes [from 8 to 24]: “)) )

See how this will stick the user in the input loop if the spokes are too few or too many? Now the portion of the code that makes the small, medium or large designation:

Page 18: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

18

(cond ( (< spokes 10) (alert “SMALL WHEEL”) )

( (and (>= spokes 10) (<= spokes 15)) (alert “MEDIUM WHEEL”) ) ( (> spokes 15) (alert “LARGE WHEEL”) )

)

Page 19: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

19

Points and List Manipulation At its core, AutoCAD is a program that manipulates graphical entities by using the association list you’ve now seen to control aspects like layer, color, etc. But from a geometric standpoint AutoCAD is all about the points. As an example any line has two controlling points while a circle has a centering point and a point on the circle that defines the circle’s radius. Our mission now is to understand how to work with the points to construct geometry. First a few basics:

Obtain a point PT1 from a user like this: (setq pt1 (getpoint “\nSelect a point: “)) Now get PT2 in the same way like this: (setq pt2 (getpoint “\nSelect a point: “))

You now have two 3D points stored in the variables PT1 and PT2 right?

CAR, CADR, CADDR To decompose points into their X, Y and Z coordinates you need to know how to use the CAR, CADR and CADDR functions. Let’s demonstrate:

The X value of PT1 would be: (car pt1) The Y value of PT1 would be: (cadr pt1) The Z value of PT1 would be: (caddr pt1)

Why? Because that’s how somebody defined it! Just memorize these functions and we’ll move along. LIST Now let’s say that you’d like to draw a circle with an origin point that is at the X coordinate of PT1 and the Y and Z coordinate of PT2. Further, the radius of the circle should have a value of 11.5. Here’s how that code would look:

(command “.circle” (list (car pt1) (cadr pt2) (caddr pt2)) “11.5”)

Page 20: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

20

The unexpected part here is the LIST statement, but the concept is easy considering the following:

• To build a point you must have an X, Y and Z coordinate. • The CAR, CADR and CADDR functions allow you to obtain the X, Y and Z. • The LIST function simply concatenates the coordinates together into one point • The CIRCLE command takes the point as input

Once you start thinking LIST every time you access a point and follow the basic rules above it gets easy.

Expanded Example Let’s now beef up our wheel creating program by adding a few more requirements. Here’s the pseudo code for the example:

• Prompt the user for a point for the wheel center • For small wheels use spoke length of 8, medium gets 10 and large gets 12 • Draw a first spoke at the center point • Array the first spoke with the appropriate number of spokes

Real Code

First I’ll write the code that assures user input and enforces the maximum and minimum spokes cases. This looping structure will use a WHILE function along with a complex test case like this:

(setq spokes 0) (while (or (< spokes 8) (> spokes 24)) (setq spokes (getint "\nEnter number of spokes [from 8 to 24]: ")) ) (setq wheel_center (getpoint "\nSelect center point of wheel: ")) (cond ( (< spokes 10) (command ".line" wheel_center "@8<0" "")) ( (and (>= spokes 10) (<= spokes 15)) (command ".line" wheel_center "@10<0" "")) ( (> spokes 15) (command ".line" wheel_center "@12<0" "")) ) (command "-array" "last" "" "p" wheel_center spokes "360" "y")

Page 21: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

21

How did I know how to write the ARRAY logic? Here’s a few hints:

• Use the –ARRAY command so you interact with the command prompt not a dialog box • Use the LAST object drawn to build the selection set • Use the “” to close the selections • Use the WHEEL_CENTER and SPOKES variables to pass user input to the command line • Go through the command manually to get the sequencing

A Little more Let’s now change the program so it’ll always draw the spokes on the layer WHEELS which has a color assignment of YELLOW like this: (setq spokes 0) (while (or (< spokes 8) (> spokes 24)) (setq spokes (getint "\nEnter number of spokes [from 8 to 24]: ")) ) (setq wheel_center (getpoint "\nSelect center point of wheel: ")) (command "-layer" "make" "wheels" "color" "yellow" "" "") (cond ( (< spokes 10) (command ".line" wheel_center "@8<0" "")) ( (and (>= spokes 10) (<= spokes 15)) (command ".line" wheel_center "@10<0" "")) ( (> spokes 15) (command ".line" wheel_center "@12<0" "")) ) (command "-array" "last" "" "p" wheel_center spokes "360" "y")

Again, check out the –LAYER command sequencing manually and you’ll see where I got the order of operands.

Page 22: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

22

Building Entity Sets - SSGET

Let’s say that you wanted to build a program that would find all the circles in your drawing, no matter what layer they were on and change them to a layer called CIRCLES with a bylayer color of BLUE.

First, let’s draw a circle in AutoCAD and use the GE function from the previous session to get an idea of how the circle is constructed. Here’s the resulting list from a circle entity:

((-1 . <Entity name: 7efa0390>) (0 . "CIRCLE") (330 . <Entity name: 7ef9ecf8>) (5 . "14A") (100 . "AcDbEntity") (67 . 0) (410 . "Model") (8 . "0") (100 . "AcDbCircle") (10 39.9536 25.0516 0.0) (40 . 8.1027) (210 0.0 0.0 1.0))

Note the pair (0 . "CIRCLE") which indicates entity type and (8 . "0") which indicates the layer. We know the circle has a BYLAYER color attribute because the entity list does not include a (62 . X) pair (where X would be the AutoCAD color number). I know this may all seem confusing at first, but if you use the GE function I’ve give you to explore various entities you’ll start to see the patters.

Note: You can also find out about entity list parameters in the Developer’s Help section of the AutoCAD help system.

Now let’s make the leap to building selection sets with SSGET by using an example. First we’ll look at building a set which we’ll store as a variable name called CIRCLE_SET that finds all circles in the drawing no matter what layer they are on:

(setq circle_set (ssget "x" '((0 . "CIRCLE")) ))

This is an example of selection set filtering which is denoted by the “x” in the format of the command. What comes next is a quoted list of all the associative pairs of data you’d like to look for in building the set. The fewer items in the quoted list, the more broad the search. Here’s an example of finding only circles on layer GEOM:

(setq circle_set (ssget "x" '((0 . "CIRCLE") (8 . "GEOM")) ))

What would this example find:

(setq circle_set (ssget "x" '((0 . "CIRCLE") (62 . 2)) ))

This would find circles that are yellow. Remember the (62 . X) parameter I gave you earlier?

Page 23: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

23

Where to Use This?

Anywhere you would normally require a selection set of objects like this:

(command "change" circle_set "" … change properties here ...)

or

(command "erase" circle_set "")

Don’t make it too complicated, the SSGET function simply allows you to build sets via filtering just like you would in AutoCAD … just easier that’s all!

Loading Code

After you’ve written a program and debugged it you might like to save your code in its own LSP file for your convenience. Therefore the question becomes how can you load programs into the AutoCAD environment? Well, there are a few ways that I’ll cover briefly here.

Option 1 – Using Appload

You can always load an LSP file using AutoCAD’s APPLOAD command to navigate to the file and load it in. The only problem with apploading a program is that the results of the load will be lost the next time you exit AutoCAD unless you know the trick. To use APPLOAD simply type it in at the command line.

If you want to load your program EVERY TIME AutoCAD starts simply use the Startup Suite CONTENTS button to add the program name permanently as shown at right.

Using APPLOAD has its advantages in that it is graphically oriented and easy to navigate, but to really gain control over your programs and AutoCAD’s startup using the ACADDOC.LSP gives the best results

so we’ll look at it next.

Page 24: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

24

Option 2 – Load from ACADDOC.LSP

Since the ACADDOC.LSP is automatically loaded at AutoCAD’s startup you can simply insert a line into your ACADDOC.LSP file that loads the program remotely like this:

(load “c:\\mydirectory\\myprogram.lsp”)

Where the MYDIRECTORY and MYPROGRAM parameters are simply replaced with the appropriate values. Note the \\ characters required for pathing!

Centralizing Your Code

In this case we wish to load an external AutoLISP file with some utilities in it (called UTILS.LSP) which resides on a network drive. The contents of the ADADDOC.LSP would look like this:

(if (findfile "x:\\autolisp\\utils1.lsp") ; findfile verifies that the file exists (load "x:\\autolisp\\utils1.lsp")) )

Now you’ve got a way to load files from a remote network location so the programs can be maintained in one place! This is the best way to load programs (especially if you’re a CAD manager) because you never have to visit the user’s machine to modify your utilities.

Compile Your Code

Let’s face it, if you put unprotected LSP code on your network somebody is going to hack into it and change it. Wouldn’t it be wiser to simply secure your code from tampering before this happens? You bet it would and the good news is the Visual LISP compiler allows you to do so easily.

The steps are simple:

• Know where the program you’re compiling is located (example: C:\TEST\MYPROG.LSP)

• Start the Visual LISP Integrated Development Environment by typing VLIDE at AutoCAD’s command prompt

• Compile your program using this syntax: (vlisp-compile ‘st “c:\\test\\myprog.lsp”)

Page 25: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

25

The results of this compile will be that you now have C:\TEST\MYPROG.FAS as a compiled (or Fast Load) formatted file. This file can be loaded in via the APPLOAD function or using a load command like this:

(load “c:\\test\\myprog.fas”)

Safe and secure! Now that’s better.

VLIDE Environment (and Help)

You can also write your code in the VLIDE window (see below) and get the benefit of a drop down function selector and parenthesis matching. Some programmers really like the VLIDE environment while others (myself included) prefer to use their own editing program. Either way is fine. It is simply a matter of preference.

If you do choose to dig into the VLIDE interface spend some time with the HELP utility provided with it.

Page 26: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

26

While we’re on the subject of help, use the Developer’s Help section of the AutoCAD help system and you’ll find tons of information on all the VLIDE functions and AutoLISP functions as well.

Page 27: AutoLISP® / Visual LISP® - Part 1 - · PDF fileThe AutoLISP® Vusual LISP® - Part 1 Robert Green 3 EXERCISE: Key Files, Functions and Variables To verify that you can create an

The AutoLISP® Vusual LISP® - Part 1 Robert Green

27

Materials

You can download the updated course guide, PowerPoint and video capture (with any additional notes or corrections) for this presentation at my web site www.CAD-Manager.com on the DOWNLOAD page using the password “LISP1” (without the quotes).

Feel free to email me at [email protected] with follow up questions.

Other Reference Materials You can find a wide range of information on customization, programming and CAD management at my web site: www.CAD-Manager.com

Downloads: I’ve found CAD Depot to be a very useful source for public domain AutoLISP utilities you can use as inspiration for your own routines. You can find the AutoLISP area at:

http://www.caddepot.com

Besides AutoLISP routines, there’s a lot of other nice material at CAD Depot worth some of your browsing time.

AutoLISP help: Also be sure to check out the AutoCAD help resources under the DEVELOPER GUIDE section for a wealth of information on AutoLISP commands and functions. You may even want to try working the GARDEN PATH example tutorial now that you have a bit of a grasp of how to deal with AutoLISP.