Professional Documents
Culture Documents
Class Handout SD125181 Advanced AutoLISPfrom Hack To Expert Darren Young 2
Class Handout SD125181 Advanced AutoLISPfrom Hack To Expert Darren Young 2
Learning Objectives
• Learn how to use advanced AutoLISP functions
• Understand advanced concepts like recursion
• Understand how reactors work
• Learn how to use the nearly 2000 undocumented AutoLISP functions
Description
Are you a casual LISP programmer? Do you get what you want done but feel like you have to
bludgeon your way through it? Do you have trouble getting what’s under the hood into overdrive?
Then, this class is for you. You’ll learn many of the things that real power AutoLISP programmers
know.
Speaker(s)
Based in Washington state, Darren Young has been a veteran Autodesk University speaker for
well over a decade. His unique ability to leverage multiple every day technologies in interesting
ways to solve implicated and laborious tasks has been valued by users around around the world.
Down to earth and approachable, he's always willing to help his peers anytime of the year even
outside of Autodesk University. Darren's background includes a wide variety of disciplines such
as Construction, Engineering, Manufacturing, LEAN, Information Technology, Computer
Programming, Author and Technical Editor. His lectures and labs are not just a training
opportunity for others but a venue which connects him personally with users helping him learn as
well.
Page 1
Introduction
This course is for anyone who’s casually programmed AutoLISP but knows there’s more untapped
power under the hood. At the end of this class, you’ll know exactly where to look and how to tap
into that power increasing your coding abilities and enabling you to write more functional
programs, with less code.
With ARX, VBA, and now .Net (Dot Net), there’s always a rumor flying around that AutoLISP is
dead or going away. That’s simply not true. While there are plenty of reasons to use other APIs
and languages, there’s also plenty of reasons to continue using AutoLISP and Visual LISP. For
the non-professional programmer, it’s a great, easy to learn language with plenty of power. It’s
built into AutoCAD, it can do most of what VBA can do, and you don’t have to purchase any
special development software. If you want to automate AutoCAD, AutoLISP and Visual LISP is a
perfectly suitable option. Take it for a test drive and put the petal to the floor. You’ll be amazed at
what it can do.
Page 2
Advanced AutoLISP
(apply ‘function list)
This function takes a quoted function, and applies it to a list of arguments. This can be very useful
for functions that require a list of arguments when you don’t know how many there will be. If you
know how many arguments or variables, it’s typically not needed.
(setq mylist ‘(1 3 5…etc…)) ; What if we didn’t know how many items in the list?
(apply ‘+ mylist) ; It’s still the same no matter how many items
When you have a list of raw data, it’s not practical to build a new list inserting the function
in the front of it so that it can be evaluated. It’s also not efficient (coding or processing) to loop
through that list of potentially unknown length processing each item one at a time.
This…
(1 3 5)
Or require this…
(setq number 0)
(foreach item mylist
(setq number (+ number item))
)
Page 3
But is simpler with this…
(apply ‘+ mylist))
You could use this code (imagine if there were hundreds of items in your list)…
Or this code…
When used with multiple lists, each list is processed in parallel one item at a time. Again, using
these 2 lists…
Or this code…
(mapcar '+ mylist1 mylist2)
Page 4
But what if the 2 lists contained different numbers of items? (mapcar) only processes the lists
while each list contains matching items in the other lists. In other words, it only processes the
number of items in the shortest list and ignores (with no errors) any additional items the other lists
may contain. Use this to your advantage. If we use two lists of unequal length like this…
This code…
(mapcar '+ mylist1 mylist2)
That’s all fine and good but what does this do for you the programmer? What’s it all mean? The
essence of (lambda) is that it lets you define a function on the fly at the point in your code where
it’s needed, which often makes it more understandable, and without having to create the overhead
in memory of actually defining a named function that you don’t need anymore. Think of it this
way…in Lisp programming, you create variables when you think you’ll need the value again. If
you don’t need the value, you take the value and pass it to another function. Take the following
two examples, both of which result in telling you how many seconds in a week which; we’ll assume
is the value we want to use. Would you use this code…
Using (lambda) is essentially the same thing but on the function level instead of the variable level.
You typically would not create a whole bunch of named functions all over the place (via defun)
that you would never use again unless the function was large and complex or had a specific major
purpose and objective. In these other cases, you can use the (lambda) construct instead. Let’s
Page 5
use our previous (strcase) example that we used with (mapcar) in the preceding section. (mapcar)
worked real well with (strcase) when converting to lower case. But what about uppercase?
(strcase) in that situation needs a second parameter, a T, to tell (strcase) to convert to lower case.
For (mapcar) to work it needs something extra. Let’s again use this data…
You could do something like this to pass the T along with the string to (strcase) by building a list
of T’s for each string value…
This works well because as you learned earlier, each of the lists passes its items in parallel
meaning a T goes along with each sting to (strcase). However, you could also do this…
Doesn’t seem much different does it. It’s actually less clear using (lambda). But what if you don’t
know ahead of time how many strings are going to be passed? You’ll have to create a loop that
creates enough T’s for that second list which further complicates the first example. In the second
example that uses (lambda), it doesn’t matter. We defined a function with (lambda) that adds the
T. (mapcar) then just passes each item to the function, which is accessed with the function’s
argument X.
Also, consider that the first example worked well because we just blindly passed items from the
lists to (strcase). But what if we needed to perform some type of operation on them? Mathematical
operations, conditional testing (if/cond/eq/equal/…etc…) all would not have worked unless they
were inside the (lambda) function, which could perform any number of operations in the data.
Let’s take a look at another example. This time, we’re going to give (mapcar) a list of Month names
and we’d like back from (mapcar), a list of Month names abbreviated to the first 3 letters, with the
initial letter being upper case and the last two lower case. Let’s use this as our list…
(setq months ‘(“JANUARY” “february” “March” “aPRIL” “MaY” “JUNE” “july” “AuGusT”
“SEPtember” “octOBER” “NOVEMBER” “DeCemBer”))
With this data list, (strcat) can’t do it. Neither can the (substr) function. Using them together along
with (strcat), we can do it with the following code…
Page 6
("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec")
Now wasn’t that much easier? You can even use multiple lists with (lambda), just make sure
there’s enough argument variables declared so that there’s one for each list that will be passing
values from. Again, take this for an example…
With (mapcar) and (lambda), we can easily find the midpoint between those 2 points using this
code…
This results in the point (-0.37 5.79) being returned. Notice that one of the points doesn’t have a
Z-coordinate yet the function doesn’t error out. If you’re working with 2d points, that’s a good thing.
If they both had a Z-coordinate, it would have worked with that we well. Now here’s a variation of
that same code you may see…
(mapcar (function
(lambda (c1 c2)
(/ (+ c1 c2) 2.0)
)
)
pt1
pt2
)
In this example, (mapcar) isn’t using a quoted function (‘), instead it’s using the (function) function.
This was introduced because when running compiled AutoLISP code (FAS or VLX files), if the
code fails in the right place in the right conditions, the quoted (lambda) function’s source code
could be exposed and displayed on the text screen. By wrapping it the (function) statement, it’s
protected from viewing during these types of failures. Using either form is perfectly fine, and one
is not more correct than the other. Using the quoted function is a little easier to read and typically
all that’s needed if you aren’t worried about keeping people from viewing your source code. Just
as there’s a quote function (quote) that can be used in place of the quote symbol (‘), the (function)
function does a similar thing at the function level. Now hopefully that wasn’t too confusing with all
the function functions and quote quotes.
Page 7
them or figure them out let alone mixing several altogether nested. Then, I found the need to use
the (nentsel) function, which returned nested data from a user selection. That is, I wanted
information about a coordinate of an object within a block, not information about the block. The
(nentsel) explanation in the AutoLISP reference explains the data it returns and how it’s processed
using the transformation matrix to get what you are looking for. The following code was what I
came up with after 2 days where pt1 was the point and mat was the transformation matrix as
turned by (nentsel) …
(setq pt1
(list (+ (* (nth 0 (nth 0 mat)) (nth 0 pt1))
(* (nth 0 (nth 1 mat)) (nth 1 pt1))
(* (nth 0 (nth 2 mat)) (nth 2 pt1))
(nth 0 (nth 3 mat))
)
(+ (* (nth 1 (nth 0 mat)) (nth 0 pt1))
(* (nth 1 (nth 1 mat)) (nth 1 pt1))
(* (nth 1 (nth 2 mat)) (nth 2 pt1))
(nth 1 (nth 3 mat))
)
(+ (* (nth 2 (nth 0 mat)) (nth 0 pt1))
(* (nth 2 (nth 1 mat)) (nth 1 pt1))
(* (nth 2 (nth 2 mat)) (nth 2 pt1))
(nth 2 (nth 3 mat))
)
)
)
It worked, but frustrated with the amount of effort and knowing that there must be a better way, I
posted the question on the old ACAD forum on CompuServe (now part of AOL). I don’t even recall
whom the person was any more, but this is the code they posted back that did the same thing…
As you can see, it’s a lot smaller and more efficient. It was upon viewing that code, that I committed
to breaking down this small snippet and figuring out exactly what it does and how it does it. When
you’re back at the office, try doing the same. Refer back to the (nentsel) documentation in the
AutoLISP Reference so you know what the code is attempting to do. I guarantee, that when you
go through this snippet and actually understand how it works and why, you’ll never have trouble
with (apply), (mapcar), or (lambda) ever again. Use the following blank lines to make notes as
you disassemble this code and figure out what it does.
Page 8
Recursive Programming – It’s Kind Of Like Talking To
Yourself
One of the oddest concepts that a lot of casual programmers have difficulty understanding, let
alone implementing in code is known as Recursion. The simplest example of recursion is
something most people have seen at one time or another. If you took a television camera and
recorded the television itself, and played that to that same television you were recording, you’d
see a recursive graphic. The television, would be displaying a picture of itself, displaying a picture
of itself, displaying a picture of itself, etc.
Recursion in programming is essentially the same thing, it’s when a program calls itself. Of course,
unlike the television picture that goes on and on forever, with recursive programming, you need
to have an “out” or your program would just go on forever in an endless loop until your software
or computer ran out of memory.
It’s a difficult concept to grasp beyond the basic definition of “a program that calls itself”. Anyone
can understand that, but wrapping your head around how you’d use such a technique in your
programs is a little more mind numbing. So to get you thinking about it and understanding it, let’s
look at a few examples, which might get you thinking about how you can apply this from a
programming perspective.
Suppose you built a machine that has one conveyor that fed into it, and one that fed out of it. The
machine, removes cardboard boxes to reveal the contents of the box. Boxes move down the in
feed conveyor, into the machine, the cardboard box is removed, and the contents come out on
the exit conveyor. Now, what would happen if one of the boxes contained more cardboard boxes?
As the machine processed the big box that had more, smaller cardboard boxes inside, it stopped
accepting big boxes from the feed conveyor. It then took the smaller boxes, and fed those back
into the machine again. The machine then stripped the cardboard off the small boxes, except one
of those contained even more tiny boxes. The small boxes stopped feeding into the machine, and
the tiny boxes went back in. When all the tiny boxes finished going into the machine, the small
boxes started again, and when all those were done, the large boxes started again. This process
that the machine we built was performing, can be thought of as recursion.
Now instead of a conveyor of boxes, think of data in a List. Maybe the List has strings, integers,
real numbers. Maybe some of the items are Lists and some of those may or may not contain Lists.
How would you process this data not knowing how deep it was nested? You’d build a recursive
function that processed the List, and when it encountered a nested List inside of the List, it would
halt processing the List (temporarily), while it called itself and handled the nested List and when
finished with the nested List, it would continue with the main list.
Another good example is a program that processes folders on your hard drive and finds files. You
can point it to a folder, but does that folder contain more folders? And do those folders contain
more folders? And are files scattered throughout at all levels within those “unknown” levels of sub-
folders? This would be a good case for using recursion. This is the essence of recursive
programming. Anytime you have an unknown set of potentially nested conditions or processes
you need to perform, or data you need to examine, recursive programming can come to the
rescue.
Page 9
Let’s start looking at some code. To begin with, we’ll write code that returns the factorial of the
number 4. If you’re unfamiliar with factorials, it’s the mathematical process where you take a
number, multiply it by a number one less, multiplied by a number one less until you get to 1. So,
the factorial for the number 4 is the following formula 4 * 3 * 2 * 1 = 24.
Recursion is a good option here because we don’t always know how many times we’ll need to
multiply unless we know the number beforehand. In this case we do and it’s 4 so we call the
function with the syntax (factorial 4). Now, while our formula is 4 * 3 * 2 * 1, this program takes a
slightly different approach, it works from the opposite direction, it’s actually calculating 1 * 2 * 3 *
4. If you think about it, that’s what all of your AutoLISP programs do, they work into the nested
most functions, then slowly work back.
In this case, the program doesn’t try to perform (4 * 3), it tries to perform (4 * (factorial of 3)). But
to calculate the factorial of 3, it needs to multiply it by the factorial of 2, which it also doesn’t know
and so on. What might help you understand a little better, is to list the formula so it reflects more
closely what’s going on is this…
(factorial 4) = (* 4 (* 3 (* 2 (* 1 1))))
Here’s some code that reflects this without using recursion (without the program calling itself) …
Page 10
Calling the above code (factorial4 4) will do the same thing as the recursive example. Except in
this case, instead of calling itself, it calls a completely different function that’s almost identical. As
you can see, a lot of the code is the same. And the “unknown” nature of not knowing how many
times (how deeply it’s nested) makes this a good application for recursion.
The fact that we’re dealing with numbers in this example, means that it would really not be that
hard to create a loop with a few counter variables to perform this same calculation. But not all
cases would be that easy. Let’s look at another example that deals with nested lists…
The code in this example looks for a user specified item within a list. The AutoLISP function
(member) typically handles this type of need. But if the list contains other nested lists, (member)
just doesn’t do it anymore. In this case, we’re using a function called (vl-some). This function takes
a quoted function, just like (apply) or (mapcar). The purpose of (vl-some) is to return T if the
function evaluates to T for at least 1 (one) item in the list. If the function evaluates to NIL for all
items, it returns NIL. It’s the perfect function for our needs. Next, we build our function. Just like
(mapcar), (vl-some) will be handed each item in the list, one at a time. Your function then needs
to check if that item matches what we’re looking for. That’s not hard. But what if the list item, is
another list? Our function must also check for that, and if the list item is another list, it calls itself
again to process the nested list. Now, (vl-some) itself isn’t looking for our item, our (lambda)
function is doing that. What (vl-some) does is looks for T or NIL and it returns T or NIL. (lambda)
is pasting the T and/or NILs to (vl-some).
When processing a nested list that contains our item, (vl-some) returns T but it returns it to itself
because it was called from a function it was using. And because a T was returned to it, it then
returns a T. So with our example, calling (item-in-list mylist 13) would return T while calling (item-
in-list mylist “Cat”) would return NIL because it’s not contained in any of the data in the list or
nested lists.
Now that you’ve seen a couple examples, it’s really not that hard. In fact, the hardest part of writing
a program that uses recursion, is to make sure the program has an “out” or at some point stops
processing and doesn’t just blindly call itself forever. But it takes a while; you won’t be an expert
just by reading this. You’ll become and expert only after using this technique many times. To help
you with this, here’s a little sample code. This code was posted to the AutoCAD’s Customization
discussion group years ago. It was created by Owen Wengerd (http://www.manusoft.com) and is
a very good example of short, well-written recursive program.
Page 11
(defun Str+ (source / prefix rchar)
(cond
((= source "") "A")
((= (setq prefix (substr source 1 (1- (strlen source)))
rchar (substr source (strlen source))
)
"Z"
)
(strcat (Str+ prefix) "A")
)
((strcat prefix (chr (1+ (ascii rchar)))))
)
)
What this code does, is it takes a string character and increments it. Its intent is to generate the
next revision letter based in the current revision. So let’s say your drawing is at revision “B”, calling
the function (str+ “B”) would return “C”. Calling the program with (str+ “C”) would return “D” and
so on. That’s not that hard in itself, and you wouldn’t need recursion to perform it. But what
happens when you get to revision “Z” and need to go to “AA” or you’re at revision “AZ” and need
to go to “BA”. This program handles that and that’s where the recursion comes in. So your
homework when you get back to your office is to slice and dice this program up and see how it
works. Play with it a little and see if you can truly understand what it’s doing. And if you’re really
ambitious, try modifying the program so that it works as described, but does Not use the letters
“O” (oh) and “I” (eye) which resemble 0 (zero) and 1 (one).
Of course there are more than just additional functions that make it attractive. For starters, you
can step through your code line-by-line, watching where control flows and the values of variables
as they are changed. Look at A in the following image. You can add breakpoints to your code
then use one of the buttons marked C to load the code with breakpoint information into memory.
At the bottom of the screen E, you can then call your code and it will pause at the breakpoint. The
Page 12
Watch Window B then
displays your
variable’s values (you
need to add which
ones you want to
watch) as you
manually step through
the code using the
buttons marked D.
Page 13
applications offer a lot more options, including the ability to include within them, other projects,
Lisp source code, compiled Lisp code (FAS), text files and even DCL dialog files. All this within
one file makes distributing more complex programs and applications a lot simpler. There’s even
an option to compile the Visual LISP Application in such a way that it runs in its own namespace
which means all the code and variables run in its own protected memory space. If you’ve ever
had an AutoLISP program fail because another program used the same variable name and it was
set to something different then your program expected, compiling an application to run in a
separate memory name space would solve this problem.
There’s simply a lot in the Visual LISP editor, which makes it very worth your while to learn how
to use it. Unfortunately, there’s just too much to cover completely in this course, which is why
we’ve just covered some of the major highlights that can really affect your coding productivity.
Page 14
be called when you save a drawing. The command (c:Load-My-Reactor) will create different event
reactors for the :vlr-DWG-Reactor reactor. Once you load the AutoLISP code into memory, run at
the command line Load-My-Reactor. Nothing will appear to happen but something actually did,
the Reactor had 2 different event triggers added to your drawing. When you save your drawing,
you’ll be alerted pre-save and post-save with an alert box.
;;; Load Up The Reactor
(defun c:Load-my-reactor ( / myreactor)
(vl-load-com)
(setq myreactor (vlr-dwg-reactor
"This is my SAVE Reactor"
'((:vlr-beginSave . save-pre)
(:vlr-savecomplete . save-post)
)
)
)
(vlr-add myreactor)
)
Now, because these Reactors are transient, if you close and reopen your drawing, future drawing
saves will not show the alerts unless you recreate the reactors again by running the
code again. If you want a reactor to be present all the time in your drawing file, you will want to
add code to your ACAD/ACADDOC.LSP file for this purpose.
Now, something that’s less known, is that you can add the same reactor more than once. If you
load the code above and run the command Load-My-Reactor several times, when you save your
drawing you’ll get several messages. Typically, if you are adding reactors upon drawing open,
this isn’t a big issue. But if you have code that’s manually initiated by a user, like in this example,
it’s possible to add the reactor more than once, which may cause you problems. For this reason,
it’s wise to verify if the reactor is loaded already first, before adding it to your drawing. The
following 2 functions will do this for you.
;;; VLisp Reactor - Is Reactor Loaded ?
Page 15
;;; Call: (au:vlr-loaded-p fname {rtype} {revnt})
;;; Return: T/nil
;;;___________________________________
;;; fname = Function name / 'function
;;; rtype = Reactor type / :vlr-xxxx-Reactor
;;; revnt = Reactor event / :vlr-xxx
;;;___________________________________
;;; Dependent Functions...
;;; au:vlr-fun-eq-cback
;;;___________________________________
(defun au:vlr-loaded-p (fname rtype revnt / au$reactors)
(if fname
(progn
;; Get List of Reactor Types w/Reactors Loaded - If Any
(if (vl-member-if
'(lambda (i) (eq i rtype))
(vlr-types)
)
(setq au$reactors (vlr-reactors rtype))
(setq au$reactors (vlr-reactors))
)
;; Check If Reactor Callback Loaded
(vl-some
'(lambda (i)
;; Check If Reactor Callback Loaded For Any Reactor
(vl-some '(lambda (ii)
;; Check If Reactor Callback Loaded For Each Reactor
(au:vlr-fun-eq-cback fname ii revnt)
)
i
)
)
(mapcar 'cdr au$reactors)
)
)
nil
)
)
Page 16
;;;___________________________________
;;; Dependent Functions...
;;; N/A
;;;___________________________________
(defun au:vlr-fun-eq-cback (fname robj revnt / au$revnt-list)
;; Get Reactions
(setq au$revnt-list (vlr-reactions robj))
;; If Event Specified, Restrict To Event - Else Look At All
(if revnt
;; Restrict To Event
;; If Function Name = Reactor Callback
(if (eq fname (cdr (assoc revnt au$revnt-list)))
T
nil
)
;; Else Look At all
(vl-some '(lambda (i)
(eq fname (cdr i))
)
au$revnt-list
)
)
)
The explanation of all that these two functions do and how they do it is beyond what we have time
for here in this class. However, note that the function (au:vlr-loaded-p) is the only function you
need to call. The second function is used only by the first. The comments at the heading of the
function explain how to call it, but essentially, you call the function and pass the quoted callback
function, the reactor, and the event/reaction as parameters and the code will then return T if that
function is already associated with that event or that reactor. If it’s not, then it will return NIL. With
that in mind, we can modify the Load-My-Reactor code to the following to keep it from loading the
reactors more than once.
;;; Load Up The Reactor (load only once)
(defun c:Load-my-reactor (/ myreactor)
(if
(and (not (au:vlr-loaded-p
'save-pre
:vlr-dwg-reactor
:vlr-beginsave
)
)
(not (au:vlr-loaded-p
'save-post
:vlr-dwg-reactor
:vlr-savecomplete
)
Page 17
)
)
(progn
(vl-load-com)
(setq myreactor (vlr-dwg-reactor
"This is my SAVE Reactor"
'((:vlr-beginSave . save-pre)
(:vlr-savecomplete . save-post)
)
)
)
(vlr-add myreactor)
)
)
)
Some other things that are important to know about reactors are that you shouldn’t prompt for
user input or call the (command) function in a reactor’s callback function. While it can be done
successfully in some cases, it can also cause problems because some reactors fire while
commands are still active. Don’t count on being able to do this and be prepared for problems.
Also note that just like with recursive programming, it’s possible to have a reactor fire itself. That
is, if your save reactor saved the drawing, or if an object reactor modified an object, it could fire
itself resulting in an endless loop. You’ll need to make programming considerations in your code
to check for those conditions to prevent them from occurring. The most common method is to
have your callback function check for the value in a variable, and if it’s not set, set it and proceed
with the callback function. If the event triggers itself, it’ll see that the variable is already set and
not finish. Just don’t forget to clear the flag when your code is finished processing whatever it’s
doing.
There’s a lot to reactors. Review the AutoLISP reference for the various types of reactors available
as well as their events and the various functions that help you manage reactors. If you’re
ambitious, dissect the 2 utility functions I’ve supplied and see how they work. If you can
understand the logic and workings of those 2 utility functions, you’ll have already mastered
programming reactors in Visual LISP.
These ActiveX functions provide access to the methods, and properties of the AutoCAD object
model as well as supporting functions and those that provide access to the object models of other
applications that support ActiveX. If you browse through the AutoLISP Reference (in AutoCAD’s
Developer Help), you’ll see the reactor (vlr-) and (vlax-) based ActiveX functions listed. The vlax-
based functions are more generic in nature and therefore covered fairly well in the AutoLISP
Page 18
Reference. The vla- functions on the other hand, are a different story. You won’t find a list of them
or documentation of them anywhere in AutoCAD’s help system. In fact, there’s likely not a
complete list or explanation of the vla- Visual LISP functions anywhere on the planet other the
smaller lists of certain functions that people have put in CAD books or on their CAD based web
sites. Nowhere have I found a complete list of them with explanations let alone sample code. Just
looking at the sheer number of the functions involved, this likely explains why that is. The question
then comes to mind, if these ActiveX Visual LISP functions aren’t listed anywhere, then how does
someone find out about them, let alone figure out how to use them? You’ll find out how in this
section of this course.
To start with, you’ll need to be familiar with what’s referred to as AutoCAD’s ActiveX “Object
Model”. It’s a tree like structure that holds everything related to AutoCAD. In essence, it’s a family
tree for all things AutoCAD. Other software programs that support ActiveX automation have object
models too. This “Object Model” is how an ActiveX based application defines the database
structure of AutoCAD and defines its properties and methods. Oh, yea, I almost forgot to tell you,
“Methods” are the term used for “functions” when dealing with ActiveX automation.
To give you an idea of what an object model looks like, you’ll have to go to AutoCAD’s Help
System. Navigate to the ActiveX concepts in the AutoLISP Developer Guide as shown above to
view AutoCAD’s Object Model. The links here tell you a lot about how to interact with the ActiveX
Object Model using AutoLISP.
Once you start trying to write code, you’ll also want to access a different set of more robust
documentation. You’ll be accessing this information almost constantly if you’re going to be doing
ActiveX automation from Visual LISP until you become more familiar with its use. To access this
Page 19
documentation, go and click on the file C:\Program Files\Common Files\Autodesk Shared\en-
US\acaauto.chm.
You can get a similar view of the Object Model as shown above you also have access to
additional documentation of each object and its methods, properties and events that the on-line
help won’t give you.
When you get to the Object Model in this version of Help, clicking on any of the items in the Object
Model will display information for that item. You’ll also notice by looking at the object model that
there are rectangular shapes with square corners and rectangular shapes with rounded corners.
Looking at the legend, you can see that those with square corners are a Collection and those with
rounded corners are an Object.
A Collection is really a type of object as well but it’s special in that it really doesn’t do much other
than contain and group other objects. Every Layer in AutoCAD is stored and accessed in the
Layers collection. Every Block is stored and accessed in the Blocks collection and every drawing
entity (line, arc, circle, text, dimension, etc.) is stored and accessed in either the ModelSpace,
PaperSpace collection or the Block object.
Page 20
So to start, let’s look at a Line in the Object Model (Application -> Documents -> Document ->
ModelSpace -> Line). If you look at the help for the Line object, you’ll see several Methods,
Properties and Events listed. If you look at the Properties specifically, you’ll see one of those is
for Length. From AutoCAD’s Object Model, you can directly extract a Line’s Length instead of
calculating it with the (distance) function in AutoLISP. You’ll find a lot of these useful properties
for the various entities in AutoCAD that you previously needed to calculate yourself in AutoLISP.
But now with the ActiveX functionality in Visual LISP, you can get access to a lot of this information
quicker than ever before.
But the question still remains, how do you take this information in the Visual Basic documentation
and turn it into an ActiveX function in Visual LISP? The answer is that you already have all the
information you need; you just need to know how to translate it. And the key is this…Visual LISP
ActiveX functions specific to the object model take on a predictable format. For starters, they all
start with “vla-“. Next, are you extracting a property or setting a property? If you are extracting a
property, the next part of the function is “get-“ and if you are setting a property, the next part of
the function is “put-“. And finally, the last part of the function name is the property name in VBA.
In this example, that’s “length”. So, to extract the length of a line, the name of our Visual LISP
function would by (vla-get-length).
Page 21
If you look at the documentation, you’ll see that not only is there a VBA example, but there’s an
AutoLISP example as well. Also notice in the documentation, Length is a Read-Only property.
That means you can’t “set” the property and therefore there isn’t a (vla-put-length) function in
Visual LISP. If the property was not Read-Only, there would be a corresponding vla-put-<VBA
Property> function. This format is the same for ALL properties you’ll find in the ActiveX and VBA
Reference.
Now that you know how to figure out the ActiveX functions in Visual LISP for getting or setting an
ActiveX property, the next thing to figure out is what the names of the Visual LISP functions are
for ActiveX methods. This information you also had previously. If you look back at the help
information for the Line object, you’ll see that it says it can be created with the AddLine method.
This is the key to figuring out the function name. Again, the beginning of any AutoCAD Object
Model specific function in Visual LISP starts with “vla-“. Only this time, you just add the method
name. This would make the ActiveX Visual LISP function to create a line (vla-addline). This format
holds true for ALL ActiveX methods in Visual LISP, they are named in exactly the same way.
Again, this can be verified by typing it in the Visual LISP editor, making note of the color of the
function name.
Now you’re armed with all the information you need to figure out what all the 2042 different Visual
LISP ActiveX functions are. The only thing left if to figure out how to use them but that will come
shortly. Next, we’ll explore a couple different ways other than the ActiveX and VBA Reference to
Page 22
find these types of function names. For starters, you can list all of these functions right from within
the Visual LISP editor. To do this, all you need is the Apropos function in the editor.
You’ll notice that there’s just too many entries to list all at once so to see all of them you’ll have to
search for prefix strings like “vla-a” or “vla-r”. This can come in handy, after you’ve used ActiveX
Visual LISP functions for a while and you already know how to call them but just need a quick
refresher on their spelling or need to quickly browse for a function that you know exists but don’t
quite recall how it was spelled.
The Visual Basic editor opens the Object Browser with it set to display the AutoCAD Object Model
library. Using this object browser won’t help any more than using the ActiveX Reference, it’s just
another way to access the same information.
Now that you know of several ways to find Visual Basic methods and properties and convert that
data into a Visual LISP function, the next step is to figure out how to call them. This is the most
difficult part by far of working with ActiveX objects in Visual LISP. The first task will be to get the
length of a line in AutoCAD with the (vla-get-length) function that we determined we needed earlier
to extract this type of information.
If you look at the Help section for this, you’ll see the signature for using this property is
object.length. This is how this property is used in Visual Basic. Object is the AutoCAD object that
you’re using the property on and Length is the property you’re using on that object. In Visual
Basic, there are often parameters associated with methods. Properties on the other hand are
generally just set with an “=” in Visual Basic. In the case of the Read-Only Length property, there
are no arguments that go along with it in Visual Basic. The only information it needs, is the object
that is specified prior to the property and separated with a period. In Visual LISP, this object
needs to be specified as an argument (parameter). It’s always the first argument in the
function. If the property or method as listed in the ActiveX and VBA Reference has additional
arguments or values to set, they are listed after the object argument in the same order that they
appear in the ActiveX and VBA Reference documentation.
To extract the length of a line, you would call the (vla-get-length) function passing to it a Line
object. Because you are using ActiveX methods and properties, your arguments need to be
Page 23
ActiveX arguments as well. This means
that you can’t just pass an entity name to
the function like you are used to doing in
AutoLISP but instead it must be converted
to an ActiveX object. This is done with one
of the more generic ActiveX Visual LISP
functions (vlax-ename->vla-object).
Here’s how it would look…
As any good programmer knows, error checking is always an important factor. With that in mind,
what if the operator selected something that didn’t
have a length property like a piece of Text? The
answer is by using the (vlax-property-available-p)
function that is documented in the Visual LISP
Reference. This will tell us if the property we want
to use is valid for the object selected. This function
requires the Line object and the property quoted
as an argument. Here’s how this would look with
this type of error checking…
You’ll see that by first testing what we think is a Line object; we can make certain that a Length
property is indeed available for the selected object. You should also start noticing that the vlax-
functions go hand in hand with the vla- functions.
Now that we can extract a property, let’s try setting one. This property will be the Layer property.
Using the function naming convention, we outlined earlier, the function would start with “vla-”. The
next part of the function would be “put-” because we are setting a property or “Putting” a value in
that property. Finally, the property itself is “Layer”. This would make the Visual LISP ActiveX
function (vla-put-layer).
The Layer property is not Read-Only which means it can be set with a value indicating the new
layer. But according to the format of how these functions are called, we need to specify the Line
object first so that will be our first argument to the function.
The next thing is the value for the Layer name. This would then be the second argument to the
function. Calling that function would look something like this… (vla-put-layer lineobject
layername).
Page 24
I know you’re catching on to all this so this example includes error checking. It also includes an
additional error checking function (vlax-write-enabled-p) that will tell you if the specified object is
allowed to be modified or not. This would prevent an error if for some reason a particular object
couldn’t be modified. The only thing to watch here is that the Layer you are going to change to
already exists in the drawing.
This covers extracting and setting properties quite well. The next thing we need to cover is
Methods. For this example, we’ll create a line using ActiveX in Visual LISP.
From the help for the AddLine method, you can see that Visual Basic requires two arguments. In
addition, the Object lists several possibilities. The Modelspace collection, Paperspace collection
and a Block object. That means that a Line needs to be in either Paperspace, Modelspace or part
of a Block definition. In this case, we’ll be adding it to the Modelspace collection. What this means
Page 25
is that our (vla-addline) function will need three parameters, the Modelspace object being the first
parameter, and Start Point as the second and the End Point as the third.
We’ll start with the first parameter. This is the Modelspace collection object. You can’t really just
select the Modelspace object in AutoLISP so the (vlax-ename->vla-object) function that was used
before doesn’t really help in this case. For this task, you need to start from the root of the Object
Model and that’s the Application Object. To get the application object, you can use the (vlax-get-
acad-object) function.
Now if you look at the Application Object from the Object Model in the help, you’ll see there’s an
ActiveDocument property. This gives you the object of the currently open, active document in the
Documents collection. With AutoCAD being able to have multiple documents open at once, each
open document is stored in the Documents collection. You could iterate through all the different
documents in the documents collection until you get to the one document with its Active property
set to True but this ActiveDocument property is a shortcut through all that work. Now that you
know how to get the application object, and how to get to the document level, you can figure out
how to get the document object. You’ll use the (vla-get-activedocument) function passing the
Application object as its argument.
Finally, from the Document object, you need to get to the ModelSpace object. If you look at the
Document object (not the Documents collection – remember we skipped past it with
ActiveDocument), you’ll see the Modelspace property. This property returns the ModelSpace
collection which is what we need to tell Visual LISP where to add the line. To jump to the
ModelSpace collection object, you’ll be using the (vla-get-modelspace) function that returns the
Modelspace object we need. The code we’ll eventually end up using looks something like one of
these two examples. You’ll see one takes each, one step at a time (if you think you’ll need the
Application or ActiveDocument objects again) and the other does them all at once (if you won’t
need the Application or ActiveDocument objects again later).
The next step is getting the points we need for the start and end of the line. Looking back at the
AddLine method, you’ll see it specifies the StartPoint and EndPoint as a Variant – 3 element Array
of Doubles. A “Double” is a Visual Basic data type similar to a Real number. And Array, is Visual
Basic’s equivalent to a List. And finally, a Variant, is a special Visual Basic data type that can hold
any data type (string, real, double, etc.).
This is a lot different than how AutoLISP specified points with a list of three Real numbers. It
sounds complicated but once you get used to it, it’s not a big deal. The best way to see how a
point like this is structured is to extract a point from an existing line and look at how it’s structured.
This way, AutoCAD shows you what it uses, and then you can duplicate it. Let’s look at the
endpoint of the line we previously changed the layer of using the (vla-get-startpoint) function.
Now that you have the Variant as it was returned by the StartPoint property using the code shown
in the image above, you can examine it further with the Inspect tool in the Visual LISP editor.
Page 26
As you can see, by using the Inspect tool, and double clicking on the results, you can
progressively work your way into the contents of the variable deeper and deeper to see exactly
how it’s constructed. You can also see that the end result is a list of three Real numbers. This is
where we’ll start to build our point. Next, this list needs to be built into a Safe Array. This can be
done with the (vlax-make-safearray) function. This function is called with a couple arguments
which are explained as follows…
Calling this function just initializes the array. It doesn’t actually put any data values in it. To fill the
array with values, you’ll use the function (vlax-safearray-fill). This fills the data into the array that
was just created. Once this is done, you can convert this safe array into a variant by using the
(vlax-make-variant) function. Here’s a description of (vlax-make-variant).
Page 27
After this last step, the point in now ready for use by Visual LISP’s (vla-addline) function. Here’s
how it would look to create this point in the Visual LISP editor. Notice that when the function (vla-
safearray-fill) is used, you don’t need to save its return value although you can if you like.
You can see from this image, that it’s a lot easier with this function to create a 3d point. This is
really the best way to go about it. The only reason I showed you the other method was because
there are times when working in ActiveX from Visual LISP that you’ll need to create an array in a
similar fashion when it doesn’t involve point coordinates.
So now that we have our ModelSpace collection object and our two points for the start and ending
of the line, we’re ready to use the (vla-addline) function to create a new line in AutoCAD. This is
done by calling the function as we discussed earlier and looks something like this…
If you are familiar with the AutoCAD Object Model and follow the procedures demonstrated here,
you’ll have enough information to find out what the Visual LISP ActiveX function is named, and
you’ll be able to find out how to call it. Just remember that if a particular function requires an
argument and you don’t understand what format it’s looking for, the easiest thing to do is to create
the same thing manually in AutoCAD. Using Visual LISP and its editor, you can then extract the
existing value of what you created manually to figure out what you need to do in your code. It’s a
simple technique but it’ll have you lots of headaches in the end.
Page 28