PDA

View Full Version : AutoLISP 101 - Command Expressions (basic error handling and local functions)



peter
2017-09-13, 05:53 PM
Before I dig into Entity Lists...

I thought I might talk a little about the command expression (and command-s and vl-cmdf too)

They allow the user to run AutoCAD commands, which sometimes can do things that LISP (or VisualLISP) cannot do.

To me it is the LAST choice to do something.

I prefer to use ActiveX, then entity methods and finally the command pipe (or throat).


So how can we use the command expression.


(command "line" pause pause "")

The pause argument waits for user input or selection.

If you do not like to see the prompts you can set the system variable "cmdecho" to 0 (or 1 to see)

That way you can add your own prompts.



(defun C:L1 (/ intCMDEcho)
(setq intCMDEcho (getvar "cmdecho"))
(setvar "cmdecho" 0)
(command "line" pause pause "")
(setvar "cmdecho" intCMDEcho)
)


The only problem with this is escaping the command expression will cause the cmdecho to remain off.

So the following code includes an error function that runs if you escape the command expression and
changes the system variable back to the original value. This is also a good example of creating a local
function inside another function.



(defun C:L1 (/ intCMDEcho *Error*)
(defun *Error* (X)
(setvar "cmdecho" intCMDEcho)
)
(setq intCMDEcho (getvar "cmdecho"))
(setvar "cmdecho" 0)
(command "line" pause pause "")
(setvar "cmdecho" intCMDEcho)
)


In there are both the Command-S and VL-Cmdf expressions that are similar syntax.

VL-cmdf is nice because it check to make sure the expression works before running it so I use it.

You need to run the (vl-load-com) expression to load VisualLISP.

I just make it the very last line of code in my files like.



(defun C:L1 (/ intCMDEcho *Error*)
(defun *Error* (X)
(setvar "cmdecho" intCMDEcho)
)
(setq intCMDEcho (getvar "cmdecho"))
(setvar "cmdecho" 0)
(vl-cmdf "line" pause pause "")
(setvar "cmdecho" intCMDEcho)
)
(vl-load-com)