Wednesday, November 02, 2011

LISP programming primer

I received a request from a client asking me to look at a LISP program he wrote that did not work correctly. I said yes and received the following code:

(COMMAND "osnap" "End,Mid,Cen,Node,Quad,Int,Ins,Perp")

LISP and all programming languages require a certain syntax when writing code for it to work. The above code did not conform to the needed syntax. Here is the corrected version:

(defun C:MYOS (/)
(setvar "OSMODE" 255)
; CODE FOR END, MID, CEN, NOD, QUAD,
; INT, INS, PERP OSNAPS
)

The first rule of LISP, everything HAS to be in parentheses. The second rule is that each set of parentheses gets evaluated individually. The third rule is that all LISP functions must be defined with a DEFUN command.

The C:MYOS defines a function that can be launched from the command line by typing MYOS and then ENTER. The (/) indicates that no arguments or local variables are being used. The SETVAR command is used to modify AutoCAD variables like OSMODE which is responsible for the active OSNAPS in your AutoCAD session. Each combination of OSNAPS will have a unique code. The AutoCAD documentation explains this variable very clearly. The text following the semicolon is a LISP comment which is ignored by AutoCAD when running the function.

An alternative to this simple little function is to script the operation is a file like MYOS.SCR. In Notepad, type the following text with NO spaces at the end of each line and press ENTER at the end of each line as well.



Scripting is handy for some operations but can be tricky at times. The underscore + dash before the OSNAP command are used to internationalize the script (any non-english AutoCAD will recognize it) and to deactivate the dialog box so that the answers are sent as plain text.

In both scenarios, write your code in Notepad and then drag and drop the file into your AutoCAD session to load it. The LISP function must be launched on the command line but the script will run automatically if no command is already active.

Hours and hours of fun are possible when you start dipping into automation. Not for the faint of heart!!!

Happy coding!

No comments: