Saturday, July 15, 2023

AutoCAD Programming using AutoLISP

What is LISP

LISP stands for "List Processor". It is a programming language that was developed in the late 1950s by John McCarthy. It is one of the oldest high-level programming languages still in use today. LISP is known for its unique syntax, which is based on nested parentheses and prefix notation.

LISP has found applications in various domains, including artificial intelligence, natural language processing, and symbolic mathematics. It has been used for academic research, commercial software development, and prototyping new programming language concepts. LISP has been influential in the development of other programming languages and has inspired many dialects and variants over the years. Some notable LISP dialects include Common Lisp, Scheme, and Clojure.


What is AutoLISP

AutoLISP is a dialect of the LISP programming language that is specifically designed for extending the capabilities of AutoCAD, a popular computer-aided design (CAD) software. AutoLISP allows users to automate repetitive tasks, create custom commands, and add new functionality to AutoCAD.

AutoLISP is a procedural programming language, which means it follows a step-by-step approach to executing instructions. It provides a set of functions and commands that can be used to interact with AutoCAD's drawing objects, manipulate geometry, modify settings, and perform various operations.

With AutoLISP, you can write scripts and programs that automate tasks such as creating objects, modifying attributes, generating reports, and implementing custom design algorithms. These programs can be executed within the AutoCAD environment, providing users with the ability to tailor AutoCAD to their specific needs and streamline their workflows.

AutoLISP programs are typically written in plain text files with a ".lsp" extension. They can be loaded into AutoCAD using the "Appload" command, which makes the functions and commands defined in the AutoLISP program available for use within the software.

AutoLISP has a rich set of built-in functions for manipulating lists, strings, numbers, and other data types. It also provides control structures such as loops and conditionals to enable decision-making and repetition in your programs. Furthermore, AutoLISP supports the use of variables, user-defined functions, and error handling mechanisms. By leveraging AutoLISP, users can enhance their productivity, automate repetitive tasks, and extend the capabilities of AutoCAD according to their specific requirements.


Structure of AutoLISP Syntax

The syntax of AutoLISP follows the general principles of the LISP programming language but with specific features tailored for use within AutoCAD. Here are some key aspects of AutoLISP syntax:

1. Parentheses: AutoLISP uses parentheses extensively to denote function calls and to structure expressions. Each function call is enclosed in parentheses, with the function name followed by its arguments.

   Example: `(setq x (+ 2 3))`

2. Prefix notation: AutoLISP uses prefix notation, which means the function name precedes its arguments. This differs from traditional infix notation used in many other programming languages.

   Example: `(+ 2 3)` instead of `2 + 3`

3. Lists: AutoLISP treats code and data structures uniformly using lists. A list is enclosed in parentheses and can contain any number of elements, which can be atoms (symbols or numbers) or nested lists.

   Example: `(setq mylist '(1 2 3))`

4. Symbols and variables: Symbols in AutoLISP are used to represent variables, function names, and special operators. They are typically strings of alphanumeric characters and can include special characters like dashes and underscores.

   Example: `(setq radius 5)`

5. Quoting: To prevent the evaluation of expressions, the quote function (') or the backquote syntax (`) is used to quote the following expression. This is useful when you want to treat an expression as data rather than executing it.

   Example: `(setq mylist '(1 2 3))`

6. Functions and special operators: AutoLISP provides a wide range of built-in functions and special operators for performing various operations. Functions are invoked by enclosing the function name and its arguments in parentheses.

   Example: `(setq sum (+ 2 3))`

7. Variables and assignments: Variables in AutoLISP are created using the `setq` function, which stands for "set quote." It assigns a value to a symbol, creating a variable or updating its value.

   Example: `(setq x 10)`

8. Control structures: AutoLISP supports control structures like conditional statements and loops for program flow control. The `if` function is used for conditional branching, while the `repeat` and `while` functions are used for creating loops.

   Example:

   ```

   (if (> x 5)

       (setq result "Greater than 5")

       (setq result "Less than or equal to 5"))

   ```

These are some of the fundamental elements of AutoLISP syntax. Understanding these aspects will help you write AutoLISP programs and extend the capabilities of AutoCAD.


Writing Your First AutoLISP Program


To get started with writing your first AutoLISP program, follow these steps:

1. Launch AutoCAD and open a new drawing.

2. Open the Visual LISP Editor by typing "VLIDE" in the command line and pressing Enter.

3. In the Visual LISP Editor, create a new file by clicking on "File" and selecting "New." This will open a new text editor window.

4. In the text editor window, enter the following AutoLISP code:

```lisp

(defun c:hello-world ()

  (princ "\nHello, World!")

  (princ)

)

```

This code defines a function named "hello-world" that prints "Hello, World!" to the command line. The `(princ)` function at the end is used to return control back to AutoCAD.

5. Save the file with a .lsp extension (e.g., myprogram.lsp) by clicking on "File" and selecting "Save."

6. In AutoCAD, type "APPLOAD" in the command line and press Enter. This command allows you to load AutoLISP files.

7. In the "Load/Unload Applications" dialog box, click on "Contents."

8. Click on "Add..." and browse to the location where you saved your .lsp file. Select the file and click "Load."

9. You should see a message indicating that the AutoLISP file has been loaded successfully.

10. Now, you can run your program. Type "HELLO-WORLD" in the command line and press Enter. AutoCAD will execute the program, and you should see "Hello, World!" printed in the command line.

Congratulations! You've written and executed your first AutoLISP program. This simple example demonstrates the basic structure of an AutoLISP program and how to run it within AutoCAD. From here, you can explore the extensive AutoLISP documentation and start building more complex programs to automate tasks and enhance your AutoCAD workflow.


Examples of AutoLISP Program

1. Hello world - A "Hello, World!" program is generally a computer program that ignores any input, and outputs or displays a message similar to "Hello, World!". AutoLISP offers the following functions to display messages to the user:

;'Hello World' Programming Rituals
(prompt "Hello World")
(princ "Hello World")
(prin1 "Hello World")
(print "Hello World")

(alert "Hello World")


2. Calculate Area of Rectangle

This program will ask user to enter length and width of the rectangle, the use LxB to calculate the area.

; This program calculates the area of a rectangle.
(defun c:calc-area ()
  (setq len (getreal "\nEnter the length: "))
  (setq width (getreal "\nEnter the width: "))
  (setq area (* len width))
  (prompt (strcat "\nThe area is: " (rtos area 2 2)))
  (princ)
)


3. Check type of object/entities

Knowing the type of a variable object helps in handling it within the program.

(setq p1 (getpoint "\nPick a Point: "))
(type p1)

(setq p2 (getint "\n Enter radius: "))
(type p2)


; Get last drawn entity and check its type
(setq last_drawn_obj (entget (entlast)))
(type last_drawn_obj)

4. Return total number of selected objects/entities

(setq ss (ssget)) ; make selection and save in variable ss
(sslength ss) ; return length of selected set
(alert (rtos (sslength ss))) ; display on alert window



; 




; 







No comments:

Post a Comment