Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 38 ยท Automation and Plotting

AutoLISP Basics: Variables, defun, Commands and Selection Sets

Start AutoLISP in AutoCAD: lists and prefix notation, setq, defun c:name commands, user input with getpoint and getreal, the command function, entity data, selection sets and loading .lsp files.

AutoLISP is the scripting language built into AutoCAD. With it you can write your own commands, such as DRAWBOLT, that ask for a point, compute positions, draw objects and finish with a message. It is a dialect of LISP, a language whose programs are lists of lists. That looks strange for a minute, but the rules are very few, and a small amount of AutoLISP removes a lot of repetitive clicking.

AutoCAD cannot run on this site, so the AutoLISP code in this lesson is read-only. To let you experiment, the runnable examples use a tiny JavaScript interpreter that handles a subset of the syntax (arithmetic, setq, defun, if, repeat). It is a labelled stand-in: it does not draw anything and supports none of AutoCAD's functions.

Lists and prefix notation

Everything is a list in parentheses. The first item is the function, the rest are its arguments:

LISP
(+ 2 3)            ; 5
(* 4 (+ 1 2))      ; 12
(sqrt 144.0)       ; 12.0
(strcat "A-" "WALL") ; "A-WALL"

You can type these directly at the AutoCAD command line, and AutoCAD prints the result. Remember: a point is a list of numbers, (10.0 20.0 0.0), and an angle is in radians ((* pi (/ 90.0 180.0)) is 90 degrees).

Variables with setq

LISP
(setq width 120.0
      height 80.0
      area (* width height))

setq assigns. Variable names are not declared and are case-insensitive. Strings use double quotes, nil is both "nothing" and "false", and T is true. Common data functions: list, car (first item), cadr (second), caddr (third), nth, length, append, cons, mapcar, foreach, rtos (number to string), atof, fix, abs, min, max, cos, sin, atan.

JS Stand-in: a small LISP-style evaluator (subset)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Writing a command with defun

defun defines a function. If the name starts with c:, it becomes a new AutoCAD command you type like any other. A local variable list after a slash keeps names from clashing:

LISP
(defun c:SQ ( / p1 side p2 p3 p4)
  (setq p1   (getpoint "\nLower-left corner: ")
        side (getdist  p1 "\nSide length: "))
  (setq p2 (polar p1 0.0 side)
        p3 (polar p2 (/ pi 2) side)
        p4 (polar p3 pi side))
  (command "_.pline" p1 p2 p3 p4 "_c")
  (princ))

Reading it line by line: getpoint asks the user to click a point; getdist reads a distance (with a rubber band from p1); polar computes a point at a given angle and distance; command runs a normal AutoCAD command with the arguments you give (points, strings and numbers become the answers to prompts); "_c" closes the polyline; and the final (princ) ends the function quietly so no nil is printed.

Input functions: getpoint, getreal, getint, getstring, getkword (choose from keywords, after initget), getangle, getcorner, entsel (pick one object), ssget (select several).

JS Stand-in: the geometry that polar computes for the square

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Decisions and loops

LISP
(if (> n 0) (princ "positive") (princ "not positive"))
(cond ((= k 1) "one") ((= k 2) "two") (T "many"))
(repeat 4 (princ "*"))
(setq i 0)
(while (< i 5) (princ i) (setq i (1+ i)))
(foreach item '(1 2 3) (princ item))

if takes a test, a then expression and an optional else. For several expressions in a branch use progn. cond tests clauses in order. Lists are quoted with ' so LISP does not try to run them.

Reading drawing data: entities and selection sets

Every object has an entity data list, a list of pairs with DXF group codes:

LISP
(setq e (car (entsel "\nPick a line: ")))
(setq data (entget e))
; ((-1 . <Entity name: ...>) (0 . "LINE") (8 . "A-WALL") (10 100.0 50.0 0.0) (11 140.0 50.0 0.0) ...)
(cdr (assoc 8 data))     ; layer name: "A-WALL"
(cdr (assoc 10 data))    ; start point

entmod changes an object's data and entmake creates one from a data list. For many objects, ssget creates a selection set: (ssget "X" '((0 . "CIRCLE") (8 . "A-HOLE"))) selects all circles on layer A-HOLE; use sslength and ssname to loop, ssadd to add items.

Loading and running programs

  1. Save the code as sq.lsp in a text editor (or the built-in Visual LISP editor, VLIDE).
  2. Load it with APPLOAD (and add it to the Startup Suite for every session), or type (load "C:/Lisp/sq.lsp") (forward slashes).
  3. Type SQ at the command line.
  4. To auto-load on every drawing, put code in acaddoc.lsp on the support path.

Use (vl-load-com) before the Visual LISP extensions (vlax-*, vla-*) that talk to the object model, and (setq *error* ...) to restore system variables if the user presses Esc. Many people keep a personal toolbox: a command to flip all text, one to renumber attributes, one to export a coordinate list. Check the AutoCAD documentation for the full function list.

Common mistakes

  • Unbalanced parentheses: the prompt shows 1> (the number of missing closing parentheses). Type ) to finish, then fix.
  • Using degrees where radians are required.
  • Forgetting (princ) at the end of c: functions.
  • Not declaring local variables, so names leak into other programs.
  • Using command with dialogs rather than the hyphen versions or _. prefixes.
  • Assuming object snaps work inside command: set OSMODE to 0 first and restore it afterwards.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the AutoLISP expression (* 4 (+ 1 2)) return?

    The inner (+ 1 2) is 3, and (* 4 3) is 12; AutoLISP uses prefix notation.
  2. 2. What makes (defun c:SQ ...) different from (defun SQ ...)?

    A function name beginning with c: is registered as an AutoCAD command.
  3. 3. Which unit does AutoLISP use for angles?

    Angles are in radians, so convert degrees with (* pi (/ deg 180.0)).
  4. 4. Which function returns the entity data of an object?

    entget returns the list of group code pairs; assoc and cdr pull out values.

Summary

  • AutoLISP is a list-based language; calls are written (function arg1 arg2).
  • setq assigns, defun c:name creates commands, command runs AutoCAD commands.
  • getpoint, getreal, getdist read input; entsel, entget and ssget read drawing data.
  • Load programs with APPLOAD or load, and keep angles in radians.

Next: File formats: DWG, DXF, PDF and eTransmit