Run an AutoLISP

Saving the AutoLISP File

Before we can run any programs we must make sure that the program file (.lsp file in this case) resides on the system.

If you are downloading programs from my site, the method of saving the AutoLISP file may depend on the browser you are using. For example, IE8 may prompt you to save the file directly to your computer, but I believe Firefox allows you to view the file contents in the browser itself, in which case, you can either go to File » Save Page As making sure that the Save as Type panel is set to All Files; or, you can simply copy the contents into an open Notepad file and save this as ‘filename.lsp’ (again, ensuring File Type is set to ‘All Files’).

SaveasType.png

Note that the filename used to save the source code is arbitrary and will not affect the program in any way – however, the majority of users use the function syntax (and perhaps include the program version) for convenience.

Loading the Program

Method 1: Using AppLoad

At the AutoCAD command line, type AppLoad (alternatively go to Tools » Load Application).

Select the program file as previously saved and click Load to load the program into the current drawing session. Click Close to close the Appload Dialog.

Appload.png

The command line should display whether the program has indeed loaded successfully, and any loading messages the author may have decided to include.

Loaded.png

Method 2: Using the ACADDOC.lsp

Another way to load an AutoLISP program is to include a load call in the ACADDOC.lsp.

Everytime a new drawing is opened, AutoCAD will search the Support Paths for any ACADDOC.lsp files, and will proceed to load the first one it discovers.

First we must check that an ACADDOC.lsp file exists – to do this type at the AutoCAD command line:

(findfile "ACADDOC.lsp")

If this returns a filepath, navigate to the existing ACADDOC.lsp file and in the steps that follow, amend its contents.

Else, you can create a new ACADDOC.lsp file by opening a new Notepad document (or other plain text editor) and saving it as ACADDOC.lsp in an AutoCAD Support Path (ensuring the Save As Type panel is once again set to All Files).

In the ACADDOC.lsp, add a line similar to this:

(load "C:\\MyFolder\\MyLISP.lsp" "MyLISP Failed to Load")

If the LISP file does not reside in the AutoCAD Support Path, a full filepath is needed so that the LISP file may be located; in this case, be sure to use double backslashes when specifying the path.

When finished, open a new drawing and the LISP files should load.

Note: if using this method to load many LISP files on startup is causing drawings to open slower, refer to my tutorial on the use of AutoLoad to demand load LISP files.

Method 3: Using the Visual LISP Integrated Development Environment (VLIDE)

This method is aimed primarily at developers, as the VLIDE offers many debugging utilities when writing & loading code.

To load a program using this method, type VLIDE at the AutoCAD command line. In the window that subsequently appears, go to File » Open File (alternatively, Ctrl+O), and select the previously saved file.

Now go to Tools » Load Text in Editor (alternatively, Ctrl+Alt+E)

Running the Program

If the program has loaded successfully, you can now proceed to run the program in the current drawing session.

The syntax (command name) to call the program may be displayed in the author’s loading messages, or perhaps noted in the program header. If it cannot be found in either of these locations, you can inspect the source code itself to determine the command to use.

The syntax will be located after the c: in a defun function call, for example:

(defun c:MyCommand ( )
...

In the above example, the command would be MyCommand.

If the c: does not appear after the defun function, this indicates that the function is a subfunction and is designed to be called from another program.

When the command syntax is known, it may be typed at the AutoCAD command line to invoke the program.

Loading Programs Automatically.

This tutorial aims to guide you through the various methods which can be used to load a program automatically on startup.

If you have a toolbox of LISP programs that you use regularly, it would be tedious to have to load each and every program whenever a drawing is opened. Thankfully, I shall introduce two methods to accomplish this task, each with their own advantages in different situations.

Method 1: Using the Startup Suite

This is perhaps the most user-friendly method to automatically load a program at startup, as the user needn’t have any LISP experience whatsoever.

Firstly, type AppLoad at the AutoCAD command-line (alternatively, go to Tools » Load Application).

In the dialog that subsequently appears, click on the Contents button beneath the Startup Suite heading:

Startup Suite Contents.png

A secondary dialog will consequently appear, to which programs to be loaded on startup may be added. To do this, click Add and navigate to the desired program.

Startup Suite.png

All programs listed in the above panel will be loaded every time a drawing is opened.

The method of using the Startup Suite to load programs automatically does have a few disadvantages however: should the user wish to migrate his or her programs to another computer, all programs will need to be added to the Startup Suite on the new computer.

There have also been a few known bugs surrounding the Startup Suite in past versions of AutoCAD. For these reasons, I shall introduce another method which, although requires the user to have some basic knowledge of AutoLISP, overcomes these difficulties.

Method 2: Using the ACADDOC.lsp

Upon opening a drawing or starting a new drawing, AutoCAD will search all listed support paths including the working directory for a file with the filename: ACADDOC.lsp. If one or more such files are found, AutoCAD will proceed to load the first file found.

With this knowledge one can edit or create an ACADDOC.lsp to include any AutoLISP expressions to be evaluated upon startup.

Things get a little complicated should there exist more than one ACADDOC.lsp file, so, to check if such a file already exists, type or copy the following line to the AutoCAD command line:

(findfile "ACADDOC.lsp")

Should a filepath be returned, in the steps that follow, navigate to this file and amend its contents. Else, if the above line returns nil, you can create your own ACADDOC.lsp in Notepad or the VLIDE and save it in an AutoCAD Support Path.

One clear advantage to using the ACADDOC.lsp to automatically load programs is that, upon migration, it may easily be copied from computer to computer, or indeed reside on a network to load programs on many computers simultaneously.

The Load Function

The load function will evaluate all AutoLISP expressions found within a file with a supplied filename (if found), effectively loading an program file (.lsp/.fas/.vlx) into the current drawing session.

The load function takes two arguments:

(load <filename> [on failure])

Where filename is the filename of a program file to load, and on failure is an optional argument to be returned should the program fail to load (this is usually a string or nil).

If the program file resides in an AutoCAD Support Path, the filename need only be the name of the file to load; else a full filepath is required to locate the file, for example:

File Residing in AutoCAD Support Path:

(load "MyProgram" "MyProgram Failed to Load.")
(load "MyLISP.lsp" "MyLISP Failed to Load.")

File Residing Elsewhere:

(load "C:\\My Folder\\MyProgram.vlx" "MyProgram Failed to Load.")

Note that should the file extension be omitted, the load function will add .vlx, .fas, .lsp (in that order) stopping when a file is found.

Although the on failure argument is optional, I would recommend to include it in the load statement, else the function will return an error should the file fail to load.

Using this knowledge we can populate our ACADDOC.lsp file with load statements to be evaluated when the ACADDOC.lsp file is loaded on startup.

In this way, the ACADDOC.lsp may look something like this:

(load "C:\\MyPrograms\\MyLISP.lsp" "MyLISP Failed to Load.")
(load "F:\\My Folder\\MyApp.fas" "MyApp Failed to Load.")
(load "MyProgram" "MyProgram Failed to Load.")

To aid in the construction of an ACADDOC.lsp utilising the load function I have constructed an ACADDOC.lsp Creator Program which can write statements to the ACADDOC.lsp to load all programs in a directory (and subdirectories) – saving you all the tedious typing.

One disadvantage of using the load function arises when the user wishes to load a large number of programs. This method will load every program into memory everytime a drawing is opened, hence should a large number of programs require loading, there may be a noticeable increase in the time taken to open a drawing.

To avoid this time delay, programs can be ‘demand-loaded’, i.e. loaded as and when a user needs them; for this I introduce the AutoLoad function.

The AutoLoad Function

The AutoLoad function enables a user to load an AutoLISP file when a specific command is entered at the command line. This can greatly reduce the time taken to open a drawing and the memory used should the user wish to load many programs automatically as programs are only loaded into the drawing session when required by the user.

The AutoLoad function takes the following format:

(autoload <filename> <cmdlist>)

Where filename is the name of an AutoLISP file and follows much the same rules as with the load function: should the AutoLISP file reside in an AutoCAD Support Path, only the filename is needed, else a full filepath is required.

The cmdlist is a list of commands that, upon the user typing a command present in the list, the filename supplied will be loaded into the current drawing session.

This method is best demonstrated with an example. Consider the following LISP program:

(defun c:DrawLine ( / p q )

  (if (and (setq p (getpoint "\nSpecify First Point: "))
           (setq q (getpoint "\nSpecify Next Point: " p)))
           
    (entmake (list (cons 0 "LINE") (cons 10 (trans p 1 0)) (cons 11 (trans q 1 0))))
  )
  (princ)
)

The above program will simply construct a line between two selected points; but, more importantly for this example, it may be called with the syntax: DrawLine.

Let’s assume the above code is saved to a LISP file in an AutoCAD Support Path called: LineProgram.lsp.

To demand-load this program automatically we could include this line in the ACADDOC.lsp:

(autoload "LineProgram" '("DrawLine"))

Now, upon opening a drawing or creating a new drawing, should the user type DrawLine at the command line, the LineProgram.lsp file will be loaded into the drawing session and the program will start.

Should the program file contain more than one command, additional commands may be added to the list supplied to the AutoLoad function, hence triggering the load of the supplied file upon the user typing any command present in the list.

Saved from http://lee-mac.com

Вы нашли полезный для себя код на Лиспе который делает различные штуки и хотите его использовать. Как заставить его работать? Можно выделить 3 шага.

1. Сохранение программного кода на своем компьютере.

2. Загрузка файла в AutoCAD.

3. Запуск приложения (Лиспа).

Примечание: AutoLISP программы могут быть запущены только на полной версии Автокада, они не работают под AutoCAD LT. (исключая случаи загрузки дополнительных приложений типа LT Extender и ему подобных, которые специально разработаны для запуска lisp и (или) arx приложений в среде AutoCAD LT.)

Сохранение программного кода lisp на своем компьютере

Если код выложен на сайте, а не отдельным файлом, делаем так, с помощью курсора выделяем этот код и копируем его, нажав правую кнопку мыши и выбрав пункт Копировать (или Ctrl+C).
Запускаем “Блокнот” и вставляем наш код с помощью меню Правка → Вставить (или Ctrl+V). Получим примерно такое:

lisp для autocad

И сохраняем файл. Файл можно назвать, как вам нравится, но расширение у него должно быть .LSP. Правильнее (но не обязательно) будет назвать файл так же, как названа команда в найденном Вами коде. Команде всегда предшествует префикс C: после слова defun. В примере выше видно, что команду назвали OFF2, соответственно файл называем off2.lsp. Таким образом, мы можем избежать беспорядка, т.к. будем знать, что в файле off2.lsp находится команда OFF2.
Иногда в коде представлено несколько функций. Необходимо найти “главную”. Такая функция либо имеет префикс С: либо сам автор кода уточняет  как использовать. В случае нескольких “главных” имя файла не имеет никакой разницы.

 Загрузка lisp файла в Автокад

Файл сохранили или скачали уже готовый и запускаем Автокад. Выбираем Сервис → AutoLISP → Приложения… (Tools → AutoLISP → Load) или набираем в командной строке _appload.
Мы должны увидеть диалоговое окно как представлено ниже:

Установка лиспа

И по порядку делаем так:

1. Перейдите к папке, куда Вы сохранили lisp файл.

2. Выберите файл, который Вы хотите загрузить из списка.

3. Нажмите кнопку Загрузить. (Если все прошло удачно, Вы должны увидеть надпись “off2.lsp успешно загружено”)

4. Нажмите кнопку Закрыть для завершения команды.

Или еще проще загрузить lisp файл путем перетаскивания (drag-and-drop) иконки файла в графическое окно открытого документа Автокада.

Немного теории об установке лисп

В описании практически любого кода есть такая строка где написано (defun … и потом после нее чего-то там еще. Так вот то, что там написано и есть имя функции.
Если первыми символами являются C: то функция готова к вызову из командной строки. Если такого нет, то вызывать функцию надо, заключая ее имя в круглые скобки.
Т.е. если написано (defun c:test то в командной строке набираем test, а если (defun test то пишем все тоже самое в скобочках (test) все просто!

Запуск lisp программы

Как только lisp файл загружен, вызываем команду из командной строки. Команда вызывается по ее имени. В нашем примере необходимо набрать в командной строке OFF2.

Организация библиотеки лисп файлов

Каждый раз набирать _appload для загрузки того или иного приложения не дело, да и файлов этих со временем накопится, проще будет организация свою библиотеку. Для начала условимся, что все наши файлы будем складывать в одну папку. Например, D:\MyLisp. Пропишем эту папку в путях доступа Автокада. Для этого выбираем Сервис → Настройка (Tools → Options) или набираем в командной строке _options. Переходим на закладку Файлы (Files) и раскрываем список Путь доступа к вспомогательным файлам (Support File Search Path).
Мы должны увидеть диалоговое окно, как представлено ниже:

Библиотеки lisp файлов

Используйте следующую последовательность, чтобы прописать папку в путях доступа:

1. Нажмите кнопку Добавить.

2. Нажмите кнопку Обзор и выберите целевую папку (в нашем случае, D:\MyLisp).

3. Путь к папке должен появиться в диалоговом окне.

4. Нажмите кнопку OK для завершения команды.

Теперь наша папка прописана в путях доступа Автокада. Что это нам дает? Мы можем загружать наши файлы не указывая конкретного пути, а только имя файла.
Мы можем набрать в командной строке (load “<имя файла>”) для загрузки необходимого кода, например (load “off2”). Заметьте, что добавлять расширение .lsp не обязательно, хотя и не запрещается.
А самое главное – это позволит нам создать панели с кнопками для загрузки той или иной программы. Кнопка будет иметь следующее содержание:

 ^C^C(if (null C:<команда>)(load “<файл>”));<команда>;

В нашем случае:  ^C^C(if (null C:OFF2)(load “off2”));OFF2;

Вместо текста <команда> мы должны будем подставлять имя нужной нам команды, а вместо текста <файл> имя того файла, в котором эта команда сохранена. Помните, что файл должен иметь расширение .lsp.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s