Creating AutoCAD Command Functions with autolisp
Not only can you create new AutoLISP functions, but in a similar manner, you can also create new AutoCAD commands! That is, the function name can be typed directly at the Command: prompt without using AutoLISP syntax. Creating a command-line function is simply a modified form of (defun).
Explanation: the (defun C: ) function
(defun C:name ()
<expression1>
…
<expressionn>
);end defun
Notes
- The function name argument must have a name that starts with “C:” .
- The function must be defined with a nil argument list (empty list).
- The function is invoked by typing the name at the “Command:” prompt.
Example
By modifying BOX1.LSP we can make it a command-line function:
(defun C:BOX1 ()
(setq PT1 (getpoint “Lower left corner: ”))
(setq PT2 (getpoint “Lower right corner: ”))
(setq PT3 (getpoint “Upper right corner: ”))
(setq PT4 (getpoint “Upper left corner: ”))
(command “line” PT1 PT2 PT3 PT4 “close”)
)
Command: (load “BOX1”)
C: BOX1
Command: BOX1
AutoLISP vs. AutoCAD Functions
As you create new functions in AutoLISP, you will need to decide whether you want to create a command-line function or not.
Command-line function
- Typed in directly at Command: prompt.
- User is prompted for required information.
- Result is usually to affect drawing directly.
- Cannot normally be used as a subroutine of another function.
Standard AutoLISP function
- Typed as an AutoLISP expression.
- Arguments are specified directly with the function.
- Result is usually some unique value.
- Can be used as a subroutine of other functions.
- Can be used transparently within AutoCAD commands.
Example
DegreesToRadians as AutoCAD command
Command: DegreesToRadians
Enter degrees to be converted: 180
3.14159
DegreesToRadians as AutoLISP function
Command: (DegreesToRadians 180)
3.14159
PRACTICE
Change BOX1.LSP to make it a command-line function and test it. Estimated time for completion: 5 minutes.
- A complete solution to this exercise is on your class disk as BOX1-B.LSP.