AutoLISP is a dialect of the LISP programming language built specifically for use with the full version of AutoCAD Windows, Mac, and its derivatives, like AutoCAD LT. It allows users to automate repetitive tasks, create new commands, and customize AutoCAD.
See the most commonly used autolisp functions
Here’s a quick start guide to get you up and running with AutoLISP:
Understanding the Basics:
LISP:
- Origin: LISP is one of the oldest high-level programming languages, second only to FORTRAN. It was invented by John McCarthy in 1958 as a theoretical framework for symbolic data processing.
- Core Concept: At the heart of LISP is the concept of a list. In LISP, both code and data are represented as lists. This is known as “code as data and data as code” or homoiconicity. This unique feature allows for powerful metaprogramming capabilities.
- Syntax: LISP’s syntax is both its most distinctive and, for many newcomers, challenging feature. It uses a prefix notation and is heavily reliant on parentheses. For example, instead of writing
2 + 3
, in LISP you’d write(+ 2 3)
. - Symbolic Data Processing: LISP was initially designed for symbolic data processing, making it a popular choice for artificial intelligence research in the past. It can manipulate symbols, not just numbers, allowing for operations on abstract structures and representations.
- Functional Programming: LISP is a functional programming language, which means it treats computation as the evaluation of mathematical functions and avoids changing state and mutable data.
AutoLISP:
- Tailored for AutoCAD: AutoLISP is a dialect of the LISP programming language developed by Autodesk for their product, AutoCAD. It allows users to create custom functions, automate tasks, and extend the capabilities of AutoCAD.
- Integration with AutoCAD: AutoLISP provides functions that interact directly with AutoCAD’s drawing database, enabling tasks like creating and modifying objects, querying object properties, and setting system variables.
- Loading and Running: AutoLISP scripts can be loaded into AutoCAD and run directly from the command line. This tight integration allows users to create custom commands that feel native to the AutoCAD environment.
- Visual LISP: Autodesk later introduced Visual LISP as an extension to AutoLISP, providing a modern development environment with debugging tools, an integrated editor, and a compiler that generates faster code.
Setting Up:
Launching AutoCAD:
- Starting AutoCAD: Depending on your installation and operating system, you can start AutoCAD by clicking on its icon from the desktop, Start menu, or application launcher. Ensure you have a licensed version of AutoCAD, as AutoLISP functionality is not available in trial versions or some lightweight versions like AutoCAD LT.
- Workspace: Once AutoCAD is launched, you’ll be presented with the default workspace. This workspace consists of the drawing area, command line, toolbars, and palettes. Familiarize yourself with the interface if you’re new to AutoCAD.
- Initial Setup: If you’re using AutoLISP for the first time, ensure that your AutoCAD settings allow for loading and executing LISP routines. Some security settings might prevent LISP routines from running, so it’s essential to check and adjust these settings if necessary.
Opening the Visual LISP Editor (VLE):
- Accessing VLE: The Visual LISP Editor is an integrated development environment (IDE) for writing, editing, and debugging AutoLISP programs. To open it, type
VLIDE
at the AutoCAD command prompt and press Enter ( or Tools Menu / Autolisp / Visual LISP Editor).
- VLE Interface: Once the Visual LISP Editor is open, you’ll see an interface similar to other code editors. It provides features like syntax highlighting, code completion, and debugging tools. Familiarize yourself with the layout, including the console, editor window, and toolbars.
- Creating a New File: In the VLE, you can start a new AutoLISP file by selecting
File
>New
. This will open a blank document where you can begin typing your AutoLISP code. - Saving and Loading: After writing your AutoLISP routine, save it with a
.lsp
or.vlx
extension. You can then load this file into AutoCAD to execute the routine.
The Visual Lisp editor includes
Here are some of the features and functionalities that the Visual LISP editor includes:
- Text Editor: Allows you to write and edit LISP code with syntax highlighting, which makes it easier to read and understand the code.
- Console Window: Provides an interactive LISP session where you can evaluate LISP expressions, test functions, and see the results immediately.
- Debugger: Helps you debug LISP programs by setting breakpoints, stepping through code, and inspecting variable values.
- Trace: Allows you to trace the execution of LISP functions to understand the flow of the program.
- Inspect: Lets you inspect and modify the values of LISP symbols and data structures.
- Project Management: Helps you organize and manage multiple LISP files as a project.
- Auto-Formatting: Helps in formatting the LISP code to make it more readable.
- Auto-Completion: Provides suggestions as you type, based on the functions and variables in your code.
- Integrated Help: Offers context-sensitive help for LISP functions and constructs.
- Compile and Load: Allows you to compile LISP code into FAS (Fast-Load AutoLISP) files and load them into AutoCAD.
- Error Highlighting: Highlights errors in the code, making it easier to identify and fix issues.
- Integration with AutoCAD: You can directly load and run LISP routines in AutoCAD from the VLIDE.
- API Access: Provides access to the AutoCAD ActiveX/COM API, allowing for more advanced automation and customization.
- Protection: You can protect your LISP code by compiling it into a format that’s harder to read and modify.
The Visual LISP editor provides a comprehensive environment for developing, testing, and debugging LISP routines for AutoCAD. It’s a valuable tool for anyone looking to automate tasks or develop custom tools and extensions for AutoCAD using LISP.
Your First Program:
Writing the Program in VLE:
(defun c:hello ()
(alert "Hello, AutoCAD!")
)
- Function Definition: The
(defun ...)
construct is used to define a new function in LISP. In the context of AutoLISP for AutoCAD, functions that start withc:
are recognized as commands that can be executed directly from the AutoCAD command line.
(defun c:hello ()
Here, c:hello
is the name of the function, which means it can be invoked in AutoCAD by typing HELLO
.
- Command Body: Inside the parentheses after the function name, you define the body of the function. In this case, the body contains a single command:
(alert "Hello, AutoCAD!")
- The
(alert ...)
function displays a message box with the provided string. When this function is executed, it will show a message box saying “Hello, AutoCAD!”. - Closing the Function: The function is closed with a closing parenthesis:
)
Saving the Program:
- Once you’ve typed out the program in the Visual LISP Editor (VLE), you need to save it. Go to File > Save or press Ctrl + S.
- Choose a suitable location on your computer and save the file with a .lsp extension, for example, hello.lsp.
Loading the Program into AutoCAD:
- Drag and Drop: One of the easiest ways to load a LISP routine into AutoCAD is by dragging the .lsp file directly into the drawing area of AutoCAD. This will automatically load and make the function available.
- Using APPLOAD: Alternatively, you can use the APPLOAD command in AutoCAD:
- Type APPLOAD at the command prompt and press Enter.
- In the Load/Unload Applications dialog box, click on the Browse button.
- Navigate to the location where you saved your hello.lsp file, select it, and click Open.
- Back in the Load/Unload Applications dialog box, click Load.
Executing the Program:
- After loading the LISP file, simply type HELLO at the command prompt in AutoCAD and press Enter.
- As defined in the function, you should see a message box pop up with the text “Hello, AutoCAD!”.
Congratulations! You’ve just created, loaded, and executed your first AutoLISP program in AutoCAD. This basic workflow serves as the foundation for more complex routines and custom commands you might develop in the future.
Basic Syntax:
Functions:
- Structure: In LISP and AutoLISP, functions are called using a prefix notation. This means the function name comes first, followed by its arguments, all enclosed in parentheses.
(function_name argument1 argument2 …)
For example, to add two numbers, you would use:
(+ 5 3)
This would return 8
.
- Nested Functions: Functions can be nested within other functions. The innermost function gets evaluated first. For example:
(* (+ 2 3) 4)
- This first adds 2 and 3 to get 5, then multiplies the result by 4, returning
20
.
Comments:
- Single Line Comments: In AutoLISP, anything following a semicolon (
;
) on a line is treated as a comment and is ignored by the interpreter. Comments are useful for adding explanatory notes to your code or for temporarily disabling a line of code.
; This is a comment and will not be executed
(+ 5 3)
; This adds 5 and 3
- Multiple Semicolons: Using multiple semicolons in a row is a common convention for different levels of comments, especially in larger programs. For example:
;;; This might be a header comment for a section
;; This might explain a specific function or variable
; This might be a brief note or remark
Variables:
- Setting Variables: In AutoLISP, you use the setq function to assign a value to a variable. The word “setq” stands for “set quoted,” which refers to the fact that the variable name (or symbol) is typically quoted to prevent it from being evaluated.
(setq variable_name value)
For example, to set a variable named radius
to a value of 5
, you would use:
(setq radius 5)
Using Variables: Once a variable is set, you can use it in other functions or expressions:
(setq area (* 3.14159 (* radius radius)))
- This calculates the area of a circle using the previously set
radius
variable.
Understanding the basic syntax is crucial when working with AutoLISP. Recognizing how functions are structured, how to comment your code, and how to set and use variables will provide a solid foundation as you delve deeper into AutoLISP programming.
Basic Functions:
Print:
- Function: The
(print ...)
function in AutoLISP is used to display a value or message in the command line of AutoCAD.
(print "Hello World")
- When executed, this will display “Hello World” in the AutoCAD command line.
- Note: While
print
is useful for debugging or simple messages, for more user-friendly dialog boxes, you might use functions like(alert ...)
.
Math:
- Basic Operations: AutoLISP supports a variety of mathematical operations, including addition (
+
), subtraction (-
), multiplication (*
), and division (/
).
(setq result (+ 2 3))
- This sets the variable
result
to the value of5
. Thesetq
function assigns the value to the variable, while the(+ 2 3)
part performs the addition. - Advanced Operations: AutoLISP also supports more advanced mathematical functions like trigonometry, rounding, and exponentiation. For example,
(sin angle)
would return the sine of the given angle.
Prompt User:
- Getting Strings: The
(getstring ...)
function prompts the user to input a string in the AutoCAD command line.
(getstring "\nEnter your name: ")
- The
\n
at the beginning creates a new line in the command line, making the prompt clearer for the user. Once executed, AutoCAD will wait for the user to type a response. The entered string will be the return value of the function. - Other Input Functions: AutoLISP provides various functions to get different types of input from the user:
(getint "\nEnter an integer: ")
: Prompts the user for an integer.(getreal "\nEnter a number: ")
: Prompts the user for a real number (can be a decimal).(getpoint "\nSpecify a point: ")
: Prompts the user to pick a point in the drawing.
These basic functions in AutoLISP allow you to interact with the user, perform calculations, and display results. As you become more familiar with AutoLISP, you’ll discover a wide range of functions that cater to various tasks, from simple arithmetic to complex drawing operations.
6. Control Structures:
IF Statement:
- Structure: The
if
function in AutoLISP evaluates a condition and, based on whether the condition is true or nil (false), executes the corresponding code.
(if condition
then_clause
[else_clause])
- Example:
(if (= x 10)
(print "X is 10")
)
In this example, the condition checks if the variable x
is equal to 10
. If it is, the string “X is 10” is printed to the command line. If x
is not equal to 10
, nothing happens since there’s no else clause.
- Note: The
=
function is used for numerical comparisons. For non-numerical comparisons, you’d use functions likeeq
orequal
.
Loop:
- REPEAT Loop: The
repeat
function allows you to execute a block of code a specified number of times.
(repeat number_of_times
... ; code to repeat
)
- Example:
(repeat 5
(print "This will print 5 times")
)
In this example, the message “This will print 5 times” will be printed to the command line five times in succession.
- Other Looping Constructs: While
repeat
is straightforward, AutoLISP also offers other looping constructs likewhile
andforeach
for more complex looping requirements.- WHILE Loop: Executes a block of code as long as a condition remains true.
(while condition
... ; code to execute while condition is true
)
- FOREACH Loop: Iterates over each item in a list, executing a block of code for each item.
(foreach item list
... ; code to execute for each item
)
Control structures in AutoLISP, like the if
statement and various loops, provide the means to create dynamic and flexible programs. They allow your code to make decisions, repeat actions, and process lists of data efficiently.
7. Working with AutoCAD Objects:
Get Point:
- Function: The
(getpoint ...)
function prompts the user to specify a point in the drawing. This can be used to gather input for various operations, such as drawing or modifying objects.
(setq pt (getpoint “\nSpecify a point: “))
In this example, the user is prompted to specify a point in the drawing. Once the point is selected, its coordinates (a list of X, Y, [and possibly Z] values) are stored in the variable pt
.
Relative Points: You can also get a point relative to another point. For instance, (getpoint pt "\nSpecify next point: ")
would prompt the user to specify a point relative to the previously defined pt
.
Draw Line:
- Function: The
(command ...)
function is used to invoke AutoCAD commands programmatically from within AutoLISP. It’s like typing commands in the command line, but it’s done within the script.
(command "LINE" pt1 pt2)
- In this example, the “LINE” command in AutoCAD is invoked, and two points,
pt1
andpt2
, are passed as arguments. This will draw a line between the two specified points. - Note: When using the
(command ...)
function, it’s essential to understand the sequence of prompts that the invoked command would typically present to the user. This ensures you provide the correct arguments in the right order.
Other AutoCAD Object Interactions:
- Creating Other Objects: Just as you can create a line, you can use the
(command ...)
function to create other objects like circles, arcs, and polylines. For instance,(command "CIRCLE" center_pt radius)
would draw a circle with the specified center and radius. - Modifying Objects: AutoLISP provides functions to modify existing objects. For example, you can move, copy, rotate, or scale objects based on user input or predefined parameters.
- Querying Objects: You can also use AutoLISP to query properties of objects, such as their layer, color, type, or geometric properties. Functions like
(entget ...)
and(vlax-get-property ...)
can be used for these purposes.
AutoLISP provides a rich set of functions to interact with and manipulate AutoCAD objects. This allows for automation of repetitive tasks, creation of custom drawing commands, and much more, making it a powerful tool for AutoCAD users.
Loading LISP Automatically:
For frequent AutoCAD users, it’s often beneficial to have certain LISP routines load automatically upon starting AutoCAD. This ensures that custom functions and tools are readily available without manually loading them each time. The Startup Suite is a feature in AutoCAD designed for this purpose.
Using the APPLOAD Command:
- Initiating APPLOAD:
- Start by typing
APPLOAD
into the AutoCAD command line and pressing Enter. This command opens the “Load/Unload Applications” dialog box, which is the central hub for managing LISP and other application files in AutoCAD.
- Start by typing
- Navigating to the Startup Suite:
- Within the “Load/Unload Applications” dialog box, you’ll find a section labeled “Startup Suite.” This section is specifically for adding applications that you want to load automatically every time AutoCAD starts.
- Click on the “Contents…” button located under the “Startup Suite” section. This action will open another dialog box that displays the current contents of the Startup Suite.
- Adding Your LISP File:
- In the Startup Suite contents dialog, click on the “Add…” button. This will open a file browser.
- Navigate to the location on your computer where your
.lsp
file is saved. Select the file and click “Open” or “Add” (depending on your version of AutoCAD). - Your LISP file will now be listed in the Startup Suite contents. This means that every time you launch AutoCAD, this LISP file will be automatically loaded, making its functions immediately available.
- Finalizing:
- Once you’ve added your desired LISP files to the Startup Suite, click “OK” or “Close” on the dialog boxes to finalize your changes and return to AutoCAD.
- Testing:
- To ensure that your LISP routine loads correctly, you might want to restart AutoCAD and test the functions provided by your LISP file. If everything is set up correctly, your custom commands should be available right from the start without any additional loading.
Note:
- If you update or modify your LISP file, the changes will be reflected the next time AutoCAD starts, as it will reload the file from the specified location.
- Be cautious when adding multiple or large LISP files to the Startup Suite, as this could potentially slow down the startup time of AutoCAD.
The Startup Suite in AutoCAD provides a convenient way to automate the loading of LISP routines, ensuring that custom tools and functions are always at the user’s fingertips from the moment AutoCAD is launched.
Debugging:
1. Breakpoints:
- Setting: Click on the margin next to the desired line in the VLE.
- Purpose: Pauses code execution when reached.
2. Stepping Through Code:
- Step Into (F8): Execute the next line. If it’s a function, enter it.
- Step Over (F10): Execute the next line, skipping over functions.
- Step Out (Shift + F11): Exit the current function and pause at the calling function.
3. Inspecting Variables:
- Watch Window: Add variables to monitor their real-time values.
- Hover: Place the cursor over a variable in the code to view its value.
- Immediate Window: Type and evaluate expressions or variable names instantly.
4. Managing Breakpoints:
- Toggle: Click on an existing breakpoint to remove it.
- Clear All: Use the VLE’s debugging menu to remove all breakpoints.
5. Running & Stopping:
- Start/Restart (F5): Begin or restart code execution.
- Stop (Shift + F5): Terminate the debugging session.
With these basic steps, you can efficiently debug and refine your AutoLISP scripts in the Visual LISP Editor.
See the most commonly used autolisp functions
The Bottom Line
AutoLISP allows you to customize and automate AutoCAD. With the Visual LISP Editor, even beginners can start creating and debugging their own routines. Dive into this “AutoLISP Quick Start” guide, and you’ll be on your way to enhancing your AutoCAD experience.
Remember, like any programming language, practice is key. The more you work with AutoLISP, the more comfortable and proficient you’ll become.