Lesson 4
Editors, File format, & Defun

So far, you have been executing AutoLISP expressions in two different ways:  (1) typing expressions at the AutoCAD command prompt, when doing the practice sessions, and (2) typing or copying expressions into a file then loading the file into AutoCAD, when trying out the sample programs.  From here on, we will focus more on the second method.  The practice sessions will involve longer expressions and programs so we will need to take advantage of a text editor for writing and debugging.

Text editors

AutoLISP programs are written as plain ASCII text files.  They should not include any of the extra codes that more advanced word processors use to indicate fonts, paragraph styles, subscripts, and the like.  This means that any text editor which can save files as ASCII text files will work for writing AutoLISP programs.  If you are using one of the Microsoft Windows operating systems (such as Windows 98, Windows 98ME, Windows NT 4.0, or Windows 2000) you already have two text editors which will work, Microsoft Notepad and Microsoft WordPad.  Here are a few things you should know about these two text editors.

Similarities between Notepad and WordPad

Both can save files in plain ASCII format.  Notepad does this by default.  WordPad allows you to select various formats when you use the "Save as" option (in the "Save as type" window you should select "Text document").

Both are easy to use.  They both employ the same standard editing procedures that most modern Windows based editors use for such things as cursor moves, typeover/insert, and working with blocks of text (marking, deleting, moving, and copying).  While it is true that Notepad is the simpler of the two, this has to do with features that are largely irrelevant for programming.  Most of WordPad's extra features are never used in programming.  While you will occasionally need a find-and-replace feature, other features such as italics, fonts, bullets, and special formatting features are never needed in programming.  Thus, for the programmer, there are few significant differences in features.

Neither Notepad nor Wordpad can find matching parentheses.  Often, in AutoLISP programming, you need to find the closing parentheses that matches a particular opening parentheses.  Since AutoLISP uses expressions that are often nested to a depth of many levels, pairs of matching parentheses are sometimes widely separated.  Finding them by visual examination, especially in a larger program, can be very difficult.

Differences between Notepad and WordPad

Notepad is a much smaller program than WordPad, so it loads into memory more quickly.

AutoLISP programs are most readable when they are formatted a certain way, as explained below, so it is easiest to us a mono spaced font (fixed pitch) such as Courier New, Courier, or Monospac821 BT.  While NotePad uses a mono spaced font by default, WordPad does not.  WordPad requires you to set the font for each new file that you create.  However, when a WordPad file has been saved in plain ASCII format (as a text document) and is then re-opened for editing, it uses a mono spaced font (Courier New).  Thus, you might find the use of a template file, explained below, a good way to automatically "set the font" if you use WordPad.

Wordpad has a find-and-replace feature which Notepad does not.  On certain occasions this can be quite helpful.

Notepad, running under Windows 95, is limited to approximately 60 KB, which would be in the neighborhood of 30 pages of programming (depending on the density of one's programming style).   60 KB is more than adequate for all the programs in these lessons.  However, when you finish these lessons and decide to do some "heavy duty" programming, you may find yourself writing a number of programs which are larger than 60 KB.  Notepad running under Windows NT or Windows 2000, and WordPad running under and Windows operating system, can handle files many times larger than 60 KB.

Other editors

If you are already comfortable with a word processor, such as Microsoft Word or Word Perfect, you can use it for your AutoLISP programming.  However, keep these two things in mind.  First, be sure to save your files in plain ASCII format (sometimes called "DOS" or "DOS text" format).  Second, don't attempt to use any of the word processor's advanced formatting or font features.  They have no meaning to the AutoLISP interpreter, and (if saved with the file) may make your program fail to load or run properly.  Besides, they will all be lost when you save the file in plain ASCII format.

There are some text editors which are designed for programmers and employ different methods of finding and displaying matching parentheses, which is one of the most helpful features for AutoLISP programming.

Also, Visual LISP™ includes a text editor which is specifically designed to work with AutoLISP code.  Visual LISP™ was made available at one time for $99 for use in AutoCAD Release 14, but a newer version is supplied as an integral part of AutoCAD 2000.  It is a complete programming environment with the ability to create and edit AutoLISP programs and compile those programs.  The text editing window of Visual LISP has a number of features that are helpful for programming.  For example, the text display is color coded, which can help you "see" the structure of your program; matching parentheses are easily found; and you can repeatedly undo your edits.

Recommendation

Notepad is a good place to start.  When you need to do a find-and-replace, you can temporarily load your program into WordPad.  And when you start to develop longer programs in which matching parentheses and matching quotation become more difficult to track down, you can make use of a programming editor such as the one in Visual LISP.

You can always experiment with other text editors and evaluate them as you learn more about your programming needs and personal preferences.

File format

Extension

When you write an AutoLISP program, give the file a name that has extension .LSP.  This is the default extension that AutoLISP looks for when you use the load function to copy a program from file to memory.  You can use a different extensions, but you must remember to include that extension in the load expression.

Indenting and alignment

When an AutoLISP expression contains several nested expressions and occupies several lines of text in the file, the nested expressions should be indented.  The sample programs in the first three lessons are so simple that they do not require indenting.  (They do have many nested expressions, but all of them are short enough to fit on a single line.)  Although the program would run the same whether indented or not, it is customary and very helpful to form the habit of indenting.

Indent nested expressions only two spaces, three at most.  If you indent more, and your programs have many levels of nesting (which they will, eventually), then much of your programming code has to be crowded onto the right half of the screen in your text editor.  In general, follow the format you see in the sample programs.

You can also align parallel elements in order to make your program more readable.  For example, when using a single setq function to make several assignments, you will have several variable-value pairs.  You may want to align the variables vertically for easier reading, as illustrated in the sample program at the end of this lesson.

Documentation

Every program, no matter how simple, should be thoroughly documented.  You may think that you are the only one that will ever revise your program.  Even if you are, you may come back to your program in several years and wonder why you failed to explain what you were doing.  At that point you will become a believer in documentation.

Documentation should include the name and purpose of the program, the required input and resultant output, the variable names and what they represent, the major sections of of program, and anything unique about the program.  There are two methods for placing comments in a program file.  Both of these methods are illustrated in the sample programs.

Method 1  --  place comments after a semicolon (;).  When the program is loaded into memory, everything following the semicolon (to the end of that line) is ignored.  Often a semicolon is placed at the beginning of a line so that the entire line can be used for comments.

Method 2  --  place comments between a semicolon-fence pair (;|) at the beginning and a fence-semicolon pair (|;) at the end.  Since both the beginning and end of the comments are marked, they can extend over several lines.  This method of placing comments if often used at the beginning of a program file to enclose the entire description of the program, variables, etc.  It is even possible to use this method to place short comments between two portions of program code on the same line, but this makes the line more difficult to read and is not recommended.

Putting the list of variables in alphabetical order will help you maintain the list, especially with longer programs.  As you develop the program you will be adding, removing, and renaming variables, both in the list in the documentation and the list of local variables following the defun name (see sample program below).  You will find it handy to have both of these lists arranged alphabetically.

Using a template file

Since certain parts of a program file will be the same from one file to the next, you could create a template file which includes a few items already in place, like the one illustrated below.  Each time you start a new program file, you could simply open this template and immediately save it under your desired AutoLISP program name.
 

;|

Variables:

|;

(defun
 
 

)

As you learn more about AutoLISP programming, you will want to add more items to this template, such as a heading for an error routine, headings for common major program sections, etc.

Defun

The defun function is comparable to setq.  Setq can assign a list to a variable (symbol) so that the variable can be cited later in order to retrieve the list. Similarly, defun assigns a certain set of lists (a program) to a symbol.  The symbol is later cited and the program is executed.

Here are two very simple samples which will be used in the following discussion.  The first sample defines a function, the second one defines a command.

  (defun circarea (rad) (* pi rad rad))

  (defun c:circarea () (setq rad (getreal "\nEnter radius: ")) (princ "\nArea = ") (* pi rad rad))

The syntax of the defun function consists of three parts: the name, the variable list, and the program expressions.  Each of these parts is explained below.  (Also see defun under "13 - Function related")

First argument:  name

The first argument is the name of the function, for example, "circarea" in the sample above.  The same rules that apply to naming variables apply to naming functions.  There are two types of names, function names and command names.  A function name does not begin with c:, whereas a command name begins with c:.  When you define a "function," the function is called by placing it as the first element in a list.  When you define a command, the command can be entered at the AutoCAD command prompt.  The differences are shown in the following table.
 

Defining a "function" to be 
"called" from within a program. 

Name is like a variable, 
for example, circarea 

Called by placing name first in a list 
and sending any needed values, 
for example, (circarea  0.875) 
 

Defining a "command" to be 
"run" at the command prompt. 

Name starts with c: 
for example, c:circarea 

Called by entering name at command prompt, 
then supply input when prompted. 

Can also be called like a function, 
for example (c:circarea)

The "c:" used to define a command simply notifies AutoLISP that this is a special function that should operate like a command, that is, you can run this command at the command prompt.  The "c:" has nothing to do with drive C.

Also, the "c:" is part of the name, so "circarea" and "c:circarea" are two different names and can be used at the same time without conflicting with each other.

After a function or command is defined, it can be dumped to screen the same way variables are dumped to screen, using the exclamation point, (!func, or !c:func).

Do not give a command the same name as an AutoCAD command.  Also avoid any of the external commands or abbreviations (such as DIR, EDIT, and SHELL) or abbreviations (such as L for LINE, Z for ZOOM, CO for COPY, and PL for PLINE) included in the ACAD.PGP file.  If you name your command one of these names, it will not be found by AutoCAD unless the built-in command, external command, or abbreviation is disabled.

Second argument:  variable list

In the case of a function, the second argument is a list containing the variables that will receive values when the function is called.  In the sample above there is only one variable, rad.  If there is more than one variable, then the order of the variables becomes very important.  When the function is called, the values that are sent to the function must appear in the correct order so that they will be assigned to the correct variables.  For example, a function called func1, whose variable list is (size  color) might be called as follows: (func1  "large" "green"), in which case "large" would be assigned to variable size, and "green" would be assigned to variable color.

In the case of the command, no arguments are sent to it, so the variable list is a null list (an empty list).  All values must be obtained from within the function.  As illustrated above, the user is prompted for the radius of the circle during the execution of the program.  You cannot simply omit the list, because the defun function expects the second argument to be the variable list.  In the next paragraph we explain the use of this list to establish certain variables as local variables, but for now, think of it as an empty list.

A word about global and local variables

The second argument can contain a list of local variables.  You might want to review the description of global variables and local variables in the Glossary.  Any variable can be either global or local.  It all depends on how the variable is used in the program.  On the one hand, when a program uses a variable in a global manner, that variable retains its value after the program quits.  This is handy when you want to keep a certain setting that the user has entered in his first use of the program, so it can be displayed in the prompt as the default when the program is run the next time.  On the other hand, when a program uses a variable in a local manner, that variable holds its value only while the program is running.  When the program quits, the variable is returned to nil (if it was nil to begin with), or if it had another value before the program began, it is reassigned that previous value.  All of the sample programs so far use all the variables as local variables.  While it is considered good practice to make variables local, it is also helpful while you are debugging a program to leave the variables global so that you can dump their values to screen whenever needed.

Third argument:  program expressions

After the name and the variable list you place all the program expressions.  This can be as simple as one or three expressions as illustrated above, or it may be many pages of expressions.

Practice session

At the end of the previous lesson there are fourteen formulas given.  For each of those formulas define a function that will return the desired result.  Write the program in a file having the same name as the function, load it into AutoCAD and test the program.

Here is a sample of what the first formula might look like in a file with documentation.

;|  AREABH, area of triangle when base
    and height are known
    Copyright © 1998, Ronald W. Leigh
Variables
base     Base of triangle
height   Height (altitude) of triangle     |;

(defun areabh (base height)
(* base height 0.5)
)

The above program would be placed in a file called AREABH.LSP.  It would be loaded into AutoCAD by using the expression  (load "\\xxxxxx\\areabh")  at the command prompt.  (The xxxxxx is the name of the folder on which you placed the file.  You would then call the function and send it the base and height.  For example, if the base is 12.5 and the height is 9.75, you would enter  (areabh  12.5  9.75), and the function would return 60.9375.  Be sure to test the program using other input values also.

You can have both your text editor window and the AutoCAD window open at the same time.  You can switch back and forth between them easily by using the task bar.  Or you can size both windows so you can see both programs at once.  Remember that, when you edit your program, it is changed only in memory.  You must save the edited file for the changes to be placed on disk.  Even then they are not in AutoCAD.  You must reload the file using the load function.  You will quickly get used to the sequence:  edit, save, reload in AutoCAD.

If your program does not load properly

When you use the load function to load your program, there are several things that can cause the load to fail.  Here are a few common error messages and some of their causes.

error: LOAD failed
Path incomplete or incorrect, or missing ".LSP" extension.
error: extra right paren
The number of right (closing) parentheses in your program exceeds the number of left (opening) parentheses by one or more.  The one (or several) right parentheses that you need to remove may be at the end of the program or in the middle.  (Extra right parentheses can cause this error message or other error messages, depending on where they are located.)
error: malformed list
Usually one or more missing right parentheses.  Can also be caused by one or more missing quotation marks.
error: malformed string
One or more missing quotation marks.
error: exceeded maximum string length
One or more missing quotation marks.


Sample program, presston

Dies are used in punch presses to "stamp" parts out of sheet metal.  A Hidaka 45 ton hydraulic press is shown below.

One of the calculations the die designer must make is to determine the required punching force, which depends on the kind of material (particularly its shear strength, in pounds per square inch), the thickness of the sheet (in inches), and the total length of the perimeter being punched (inches).  The formula is:

      Force (in tons)  =  thickness  x  perimeter  x  shear  /  2000

This program requests these three items from the user, then calculates (instead of dividing by 2000, it multiplies by the inverse of 2000), then reports the required punching force.  This is the minimum press tonnage.  Most designers will increase this by perhaps 30%, so the program also reports that larger tonnage.

Notice the two methods of placing comments in this program:
    ;| ... |;  --   at the beginning of the file
    ;       --   for the main section labels and line numbers

Place this program in a file called PRESSTON.LSP for loading and testing in AutoCAD.  Typical input values might be  .125 (material thickness),  15.00 (perimeter),  50000 (shear strength).  These particular values would require approximately 47 tons.  After adding roughly 30%, many designers would call for a 60 ton press.

------ marker ------ beginning of working program ------ try it out ------

;|  PRESSTON, short for PRESS TONnage
    Copyright © 1998 Ronald W. Leigh
    Requests material thickness, length of
    punch perimeter, and shear strength.
    Returns required punching force.
Variables:
perim   Total length of punch perimeter in inches
shear   Shear strength of material in pounds per sq.in.
thick   Material thickness in inches
tons    Punching force in tons         |;

;10====PROGRAM

(defun c:presston (/ perim shear thick tons)                 ;line  1

;20====GET THICKNESS, PERIMETER, SHEAR

(initget 7)                                                  ;line  2
(setq thick (getreal "\nMaterial thickness: "))              ;line  3
(initget 7)                                                  ;line  4
(setq perim (getreal "\nTotal length of punch perimeter: ")) ;line  5
(initget 7)                                                  ;line  6
(setq shear (getreal "\nShear strength of material: "))      ;line  7

;30====CALCULATE TONNAGE, REPORT

(setq tons (* thick perim shear 0.0005))                     ;line  8
(princ "\nRequired punching force = ")                       ;line  9
(princ (rtos tons 2 2))                                      ;line 10
(princ " tons (plus 30% = ")                                 ;line 11
(princ (rtos (* 1.3 tons) 2 2))                              ;line 12
(princ " tons)")                                             ;line 13
(princ)                                                      ;line 14
)                                                            ;line 15

-------- marker -------- end of working program -------- try it out --------
 
 

HOME


Copyright © 1988, 1998, 2000 Ronald W. Leigh