0
0
SolidworksHow-ToBeginner · 3 min read

How to Write an AutoLISP Routine in AutoCAD Quickly

To write an AutoLISP routine in AutoCAD, create a function using (defun) with a unique name and Lisp code inside. Save it as a .lsp file, then load it in AutoCAD using APPLOAD command to run your routine.
📐

Syntax

An AutoLISP routine starts with (defun) which defines a function. The general syntax is:

  • (defun function-name (parameters) body)

Here, function-name is your routine's name, parameters are inputs (can be empty), and body is the code executed.

lisp
(defun function-name (parameters)
  ; body of the routine
  (command "_line" (list 0 0) (list 10 10) ""))
💻

Example

This example creates a simple AutoLISP routine named drawline that draws a line from point (0,0) to (10,10) in AutoCAD.

lisp
(defun c:drawline ()
  (command "_line" (list 0 0) (list 10 10) "")
  (princ))
Output
A line is drawn from coordinates (0,0) to (10,10) in the AutoCAD drawing.
⚠️

Common Pitfalls

Common mistakes when writing AutoLISP routines include:

  • Not ending the command sequence with an empty string "", which causes the command to hang.
  • Forgetting to use (princ) at the end to suppress unwanted output in the command line.
  • Using reserved names or not prefixing custom commands with c: to make them callable.
lisp
(defun c:drawline ()
  (command "_line" (list 0 0) (list 10 10)) ; Missing "" ends command improperly
  (princ))
📊

Quick Reference

ElementDescription
(defun c:name () ...)Defines a callable AutoLISP command named 'name'
(command ...)Runs AutoCAD commands from AutoLISP
(list x y)Creates a point coordinate list
""Ends AutoCAD command input sequence
(princ)Suppresses output in command line

Key Takeaways

Use (defun c:yourname () ...) to create callable AutoLISP routines.
Always end command sequences with an empty string "" to finish commands properly.
Use (princ) at the end to keep the command line clean.
Save your code as a .lsp file and load it in AutoCAD with APPLOAD before running.
Test your routine with simple commands before adding complexity.