Using defun to Define a Function
 
 
 

With AutoLISP, you can define your own functions. Once defined, these functions can be used at the AutoCAD Command prompt, the Visual LISP Console prompt, or within other AutoLISP expressions, just as you use the standard functions. You can also create your own AutoCAD commands, because commands are just a special type of function.

The defun function combines a group of expressions into a function or command. This function requires at least three arguments, the first of which is the name of the function (symbol name) to define. The second argument is the argument list (a list of arguments and local variables used by the function). The argument list can be nil or an empty list (). Argument lists are discussed in greater detail in Functions with Arguments. If local variables are provided, they are separated from the arguments by a slash (/). Local variables are discussed in Local Variables in Functions. Following these arguments are the expressions that make up the function; there must be at least one expression in a function definition.

(defun symbol_name ( args / local_variables )
expressions
)

The following code defines a simple function that accepts no arguments and displays “bye” in the AutoCAD Command window. Note that the argument list is defined as an empty list (()):

_$ (defun DONE ( ) (prompt
"\nbye! "))
DONE

Now that the DONE function is defined, you can use it as you would any other function. For example, the following code prints a message, then says “bye” in the AutoCAD Command window:

_$ (prompt "The value
is 127.") (DONE) (princ)
The value is 127
bye!

Note how the previous example invokes the princ function without any arguments. This suppresses an ending nil and achieves a quiet exit.

Functions that accept no arguments may seem useless. However, you might use this type of function to query the state of certain system variables or conditions and to return a value that indicates those values.

AutoCAD can automatically load your functions each time you start a new AutoCAD session or open a new AutoCAD drawing file; see Automatically Load and Execute VBA Projects in the AutoCAD Customization Guide for further information on automatic loading.

Any code in an AutoLISP program file that is not part of a defun statement is executed when that file is loaded. You can use this to set up certain parameters or to perform any other initialization procedures in addition to displaying textual information, such as how to invoke the loaded function.