AutoLISP CAD Scripting: The Ultimate Reference Guide

Introduction

AutoLISP is a specialized programming language embedded in AutoCAD that allows users to automate repetitive tasks, create custom commands, and extend AutoCAD’s functionality. As a dialect of LISP (List Processing), it’s powerful for manipulating geometric data and streamlining workflows, making it invaluable for CAD professionals seeking to enhance productivity.

Core Concepts

AutoLISP Fundamentals

  • Lists: Basic data structure enclosed in parentheses ( )
  • Atoms: Basic elements (numbers, strings, symbols)
  • Functions: Operations performed on data
  • Variables: Store values for later use
  • Expressions: Combinations of functions and data that return values

Syntax Basics

ElementSyntaxExample
Function Call(function arg1 arg2 ...)(+ 2 3)
Variable Definition(setq var value)(setq radius 5.0)
Comment;; This is a comment
StringDouble quotes"Hello"
ListParentheses(1 2 3)

Data Types

TypeDescriptionExample
IntegerWhole numbers42
RealDecimal numbers3.14
StringText enclosed in quotes"AutoCAD"
ListCollection of elements(1 "text" 3.14)
SymbolNamed reference'circle
Entity NameReference to a drawing object(entlast)
Selection SetGroup of selected objects(ssget)

Essential AutoLISP Functions

Mathematical Operations

(+ 2 3)        ; Addition: returns 5
(- 10 5)       ; Subtraction: returns 5
(* 4 5)        ; Multiplication: returns 20
(/ 10 2)       ; Division: returns 5
(expt 2 3)     ; Exponentiation: returns 8
(sqrt 16)      ; Square root: returns 4.0
(sin 0)        ; Sine: returns 0.0
(cos 0)        ; Cosine: returns 1.0
(atan 1 1)     ; Arctangent of y/x: returns angle in radians

List Manipulation

(car '(1 2 3))         ; First element: returns 1
(cdr '(1 2 3))         ; All but first element: returns (2 3)
(nth 1 '(1 2 3))       ; Nth element (zero-based): returns 2
(cons 1 '(2 3))        ; Add to front: returns (1 2 3)
(append '(1 2) '(3 4)) ; Combine lists: returns (1 2 3 4)
(length '(1 2 3))      ; List length: returns 3

Conditional Logic

(if condition true-result false-result)
(cond ((condition1) result1) ((condition2) result2) (t default-result))
(= 1 1)       ; Equality: returns T
(/= 1 2)      ; Inequality: returns T
(< 1 2)       ; Less than: returns T
(> 2 1)       ; Greater than: returns T
(and expr1 expr2)   ; Logical AND
(or expr1 expr2)    ; Logical OR
(not expr)          ; Logical NOT

Variable & Symbol Operations

(setq var value)       ; Assign value to variable
(set 'var value)       ; Alternative assignment
(setvar "VARNAME" value) ; Set AutoCAD system variable
(getvar "VARNAME")     ; Get AutoCAD system variable value

AutoCAD-Specific Functions

Drawing Entity Functions

(command "LINE" pt1 pt2 "")   ; Draw a line
(command "CIRCLE" center radius) ; Draw a circle
(entmake entity-data-list)    ; Create a new entity
(entmod entity-data-list)     ; Modify an existing entity
(entdel entity-name)          ; Delete an entity
(entget entity-name)          ; Get entity data

Selection Functions

(ssget)                   ; Interactive selection
(ssget "X" filter-list)   ; Selection with filter
(ssget "P")               ; Previous selection
(ssget "L")               ; Last created entity
(sslength selection-set)  ; Count objects in selection
(ssname selection-set index) ; Get entity name at index

Geometry Functions

(distance pt1 pt2)        ; Distance between points
(angle pt1 pt2)           ; Angle from pt1 to pt2
(polar pt angle distance) ; Point at angle and distance
(inters pt1 pt2 pt3 pt4 [onseg]) ; Intersection point

User Interaction

(getpoint [pt] [msg])     ; Get point from user
(getdist [pt] [msg])      ; Get distance from user
(getangle [pt] [msg])     ; Get angle from user
(getstring [cr] [msg])    ; Get string from user
(getint [msg])            ; Get integer from user
(getreal [msg])           ; Get real number from user
(initget [bits] [string]) ; Initialize user input options
(alert "message")         ; Display alert box

Step-by-Step Processes

Creating a Simple AutoLISP Function

  1. Open a text editor
  2. Define your function:
    (defun c:MyCommand ()  (alert "Hello AutoCAD!")  (princ))
    
  3. Save with .lsp extension (e.g., mycommand.lsp)
  4. Load in AutoCAD: (load "path/to/mycommand.lsp")
  5. Run by typing MyCommand at the command line

Drawing a Rectangle with User Input

(defun c:MyRect ()
  (setq pt1 (getpoint "\nFirst corner: "))
  (setq pt2 (getcorner pt1 "\nOther corner: "))
  (setq x1 (car pt1))
  (setq y1 (cadr pt1))
  (setq x2 (car pt2))
  (setq y2 (cadr pt2))
  (command "RECTANGLE" pt1 pt2)
  (princ)
)

Creating a Custom Batch Processing Function

(defun c:BatchProcess ()
  ; Get selection set
  (setq ss (ssget "X" '((0 . "CIRCLE"))))
  (if (not ss)
    (alert "No circles found!")
    (progn
      ; Process each entity
      (setq count (sslength ss))
      (setq i 0)
      (repeat count
        (setq ent (ssname ss i))
        (setq entdata (entget ent))
        ; Modify each circle (e.g., change color to red)
        (setq entdata (subst (cons 62 1) (assoc 62 entdata) entdata))
        (entmod entdata)
        (setq i (1+ i))
      )
      (alert (strcat (itoa count) " circles processed!"))
    )
  )
  (princ)
)

Advanced Techniques

DCL (Dialog Control Language) Basics

DCL is used to create custom dialog boxes for AutoLISP applications.

; DCL file (dialog.dcl)
my_dialog : dialog {
  label = "My Custom Dialog";
  : edit_box {
    key = "input_value";
    label = "Enter value:";
    value = "0.0";
  }
  : button {
    key = "ok";
    label = "OK";
    is_default = true;
  }
}

; AutoLISP to load dialog
(defun c:MyDialog ()
  (setq dcl_id (load_dialog "dialog.dcl"))
  (if (not (new_dialog "my_dialog" dcl_id))
    (exit)
  )
  (action_tile "ok" "(done_dialog 1)")
  (start_dialog)
  (unload_dialog dcl_id)
  (princ)
)

Working with External Files

; Write to file
(setq file (open "data.txt" "w"))
(write-line "Hello, AutoCAD!" file)
(close file)

; Read from file
(setq file (open "data.txt" "r"))
(while (setq line (read-line file))
  (princ line)
  (princ "\n")
)
(close file)

Error Handling

(defun safe_function (/ old_error result)
  (setq old_error *error*)
  (defun *error* (msg)
    (alert (strcat "Error: " msg))
    (setq *error* old_error)
    (princ)
  )
  
  (setq result
    (progn
      ; Your code here that might cause an error
      (/ 1 0) ; This will cause an error
    )
  )
  
  (setq *error* old_error)
  result
)

Comparison: AutoLISP vs. Other CAD Scripting Methods

FeatureAutoLISPVBA.NETPython (PyAutoCAD)
Learning CurveModerateModerateSteepGentle
Integration with AutoCADNativeGoodExcellentGood
PerformanceGoodGoodExcellentVaries
UI CapabilitiesLimited (DCL)GoodExcellentLimited
Cross-PlatformYesWindows OnlyWindows OnlyYes
Modern Language FeaturesLimitedLimitedExtensiveExtensive
Community SupportEstablishedDiminishingActiveGrowing

Common Challenges and Solutions

Challenge: Slow Performance with Large Operations

Solution:

; Turn off screen updates for faster processing
(setvar "CMDECHO" 0)
(setq old_osmode (getvar "OSMODE"))
(setvar "OSMODE" 0)
; ... your code here ...
; Restore settings
(setvar "OSMODE" old_osmode)
(setvar "CMDECHO" 1)

Challenge: AutoLISP Functions Not Loading

Solution:

  1. Check file paths
  2. Ensure syntax is correct
  3. Add to startup suite:
    (autoload "path/to/function.lsp" '("function1" "function2"))
    

Challenge: Accessing Non-Graphical Objects

Solution:

; Access layout information
(setq layouts (vla-get-Layouts 
                (vla-get-ActiveDocument 
                  (vlax-get-acad-object))))

Challenge: Complex String Manipulation

Solution: Use Visual LISP string functions:

(vl-string-search "find" "string to find in")
(vl-string-subst "new" "old" "string with old text")
(strcat "string1" "string2")
(substr "string" start [length])

Best Practices

Code Organization

  • Group related functions in a single file
  • Use meaningful function and variable names
  • Add comments to explain complex logic
  • Use proper indentation (2-4 spaces per level)
  • Follow naming conventions:
    • c:FunctionName for command functions
    • *variable* for global variables
    • Use namespace prefixes for library functions

Performance Optimization

  • Minimize calls to AutoCAD commands
  • Batch operations instead of individual ones
  • Use entity modification instead of deletion and recreation
  • Pre-compute values outside of loops
  • Use appropriate data structures (e.g., association lists for lookups)

Debugging Tips

  • Use (princ) to output values
  • Create a debug function:
    (defun debug (msg val)  (princ (strcat msg ": "))  (princ val)  (princ "\n")  val)
    
  • Test functions individually before integrating
  • Use Visual LISP IDE for step-through debugging
  • Check variable types with (type var)

Maintenance

  • Document function purpose, inputs, and outputs
  • Version your code with revision history
  • Back up your code regularly
  • Create reusable libraries for common tasks
  • Test thoroughly before deployment

Resources for Further Learning

Books

  • “AutoLISP Developer’s Guide” (Autodesk Official)
  • “Customizing AutoCAD with AutoLISP” by Bob McFarlane
  • “Practical AutoLISP Programming” by Rod R. Rawls

Online Resources

Forums

Sample Libraries

  • Lee Mac’s AutoLISP Library
  • CAD Studio’s LISP Utilities
  • JTB World’s AutoLISP Collection

Remember that AutoLISP development is an iterative process. Start small, test thoroughly, and gradually build more complex functionality. Many CAD professionals have created extensive libraries of AutoLISP routines throughout their careers to automate their specific workflows.

Scroll to Top