Ошибка неверный тип аргумента vla object nil

OK, so I guess the version that outputs this wouldn’t be any good?

Coordinate dump with LAYER
Line on layer 0
5.5138,14.1206,0.0000,10.8269,13.3799,0.0000
2dPolyline on layer 0
13.4834,15.4170,0.0000,14.4623,16.4663,0.0000,15.8001,16.6824,0.0000,16.6420,16.0676,0.0000,17.4373,15.5404,0.0000,18.8165,16.1499,0.0000,20.3718,16.9911,0.0000,21.1669,16.9596,0.0000
Polyline on layer 0
13.1745,12.7317,0.0000,14.8425,14.1206,0.0000,19.4142,11.0342,0.0000,21.0823,13.3799,0.0000
3dPolyline on layer 0
8.1086,6.9909,0.0000,10.2709,9.7996,0.0000,14.5645,7.7008,0.0000,15.7383,10.1391,0.0000

wrote in message news:5633644@discussion.autodesk.com…
Jeff,
Not 3d polylines. Individual pline segments. The cross sections were
created in LDD and displayed in 2D. The z value is redundent because all I
need is the X and Y. I have this other routine that will export all the
vertices of a polyline but not the layer (see attached).

KH

Hello everyone!

I don’t understand why I’m getting this error, when I’m trying to incorporate the IF function.

Command: TEST
Error: bad argument type: VLA-OBJECT nil
;;
;;D:Program FilesAutodeskAutoCAD 2015Fonts - path for ACAD .shx files
;;D:Fonts - My path
;;C:WindowsFonts - path for windows .ttf files

;; Optional: Make the new style Active 
;;(vla-put-activetextstyle acadDoc objStyle)


(defun c:test ()
(vl-load-com) 
(setq acadApp (vlax-get-Acad-object)) 
(setq acadDoc (vla-get-ActiveDocument acadApp)) 
(setq styles (vla-get-textstyles acadDoc))

;; Add the style named:
   (setq st-name "VLD_simplex")
   (if (not (tblsearch "STYLE" st-name)) 
   (
   (setq objStyle (vla-add styles st-name))
;; Assign fontfile to the style:
   (setq ff "D:\Program Files\Autodesk\AutoCAD 2015\Fonts\simplex8.shx") ;fontfile path here 
   (vla-put-fontfile objStyle ff)
   );then
   (princ (strcat "n " st-name " style already defined!" ));else
   );if

(princ)
)

Issue

You received an error message beginning with the words Error: ‘Bad argument type’. Here are some examples:

  • Error: ‘Bad argument type: Numberp nil’
  • Error: ‘Bad argument type: Stringp nil’
  • Error: ‘Bad argument type: VLA-object nil’
  • Error: ‘Bad argument type: lentityp nil’
  • Error: ‘Bad argument type: VLA-object-collection’
  • Sys-error: ‘Bad argument type: 2D/3D point: nil’
  • Error: ‘Bad argument type: consp nil’
  • Error: ‘Bad argument type: INT nil’

Solution

You might see any number of possible errors that begin with Bad argument type, Before getting into the specific error you saw, it’s important to go through a few simple troubleshooting steps:

• What to do first when you see a Bad Argument Type error

If you receive any error message that includes the text «bad argument type» – including all specific error messages listed on this page – go through the following three steps before getting into any of the various bad argument type error messages listed below. Any bad argument type error can potentially stem from either drawing corruption or a bug in the code, so you’ll need to either rule out or resolve these two causes first.

Step 1: Take a screenshot of the error report

Immediately after receiving the error, press the F2 key on your keyboard. Pressing F2 will open the error report in your AutoCAD Command line, and you’ll be able to see actually generated the bad argument error. It’s important that you take a screenshot of the error report in the Command line and save it to your desktop. You may need it later to figure out what caused the error, and we may ask you to send that screenshot to our tech support team to help us diagnose the issue. 

Closed the error message already? No worries – just do the same thing you did to get the error (place a plant, select a valve, etc.). The error will likely pop up again and you can press F2 and screenshot the error report.

Step 2: Rule out, or address, drawing corruption

Bad argument type errors often result from corruption in your drawing. To check for corruption, open a fresh new DWG drawing file and try the same action that generated the error. For example, if you saw the error immediately after placing a plant or setting your drawing scale, do that same thing in the blank drawing. 

***Important***: It’s crucial that you follow our specific steps to duplicate an error in a blank drawing.

  • Did you get the same bad argument type error in the blank drawing? If so, move on to Step 3.
  • Were you able to complete the same action in the blank drawing without generating the error? If so, the issue is almost certainly the result of drawing corruption. Here’s what to do:

1. Open the file where you first saw the error, and follow our steps to clean your drawing.

2. Configure our recommended settings for showing Proxy information. These settings will help you determine whether your drawing file is still corrupt.

3. Open the cleaned drawing file. If you configured the Proxy information settings correctly, you should see a Proxy Information dialog box immediately. Does this dialog box show no Proxy Objects? If so, your file is clean. Now try the same action (placing a plant, setting the scale, etc.) that generated the error.

  • No error? You’ve resolved the issue.
  • Still getting a bad argument type error? Move on to Step 3.  

Step 3: Check for a bug in the code

Once you’ve either ruled out or addressed drawing corruption, it’s time to check whether the error is the result of a bug in the code of our software.

Note that a bad argument type error will always mean that a variable in the code is not what the system is expecting. In fact, it could be the result of a simple bug – the most common of which is a typo in the code. In this case, the “object” in question may be just fine, but the variable name was mistyped in the code. (Yes, even programmers are human!) So of course the misspelled version is certainly not an object reference and is therefore nil – hence the error message.

The easiest way to check for a bug is to check our list of recent updates.

  • Don’t see a recent update that’s related to what you tried to do when you saw the error? You’ve likely ruled out a bug. It’s time to locate and address the specific bad argument type error message you’re seeing.
  • Do you see a recent update that’s related to what you tried to do when you saw the error? If so, there’s a good chance you’ve detected a bug in the code. For example, if you saw a bad argument type error when you attempted to place a Reference Note Callout, and a recent update has to do with Reference Note Callouts, there’s your bug! If you think you’ve found a bug, please let us know by sending us a technical support ticket. Make sure to include the following items in the ticket:

    • The exact text of the error message, and a screenshot of the error message (if you have it)
    • A description of the action you took that generated the error message (such as placing a plant, editing a detail, etc.)
    • A screenshot of the error report you generated by pressing the F2 key after seeing the error message. Don’t have a screenshot? Just do the same thing that caused the error. You’ll see the bad argument type error message. Press F2 now, and take a screenshot of the entire AutoCAD Command line. Include this screenshot in the technical support ticket.

Based on your ticket, we’ll take a look at the code and determine whether there is indeed a bug. If so, we’ll get right on repairing it in an update. You’ve helped us improve the software!

 Close

Specific ‘Bad Argument Type’ Errors

If you went through the «What to do first» steps above and are still seeing the error, it’s time to get into the specific Bad argument type error you’re seeing.

We’re continually logging the causes and solutions of new Bad argument type errors as we see them. Here are the specific ones we’ve seen:

• Error: ‘Bad argument type: Numberp: nil’

  • If you saw this error when trying to use our Nuke tool, your Proxy settings are configured incorrectly. Please follow our recommendations for the Proxy settings in the Options dialog box. You should then be able to Nuke properly.
  • Are you getting this message when using our Verify tool for Lighting? If so, make sure you don’t have any looped wire sections in your wire paths to fixtures.
  • Otherwise, this error will invariably be the result of drawing corruption. Follow our steps to clean your drawing.

 Close

• Error: ‘Bad argument type: Stringp nil’

You might see this error when you:

  • Tried to use our Verify Labels tool, or when working specifically with plants.
  • Had our Color Render tool turned on.
  • Attempted to open AutoCAD or F/X CAD, and it completely froze.
  • Tried to add a dripline hatch to your project.
  • Tried to place a block from our Discipline Graphics library

As you can see, this particular Bad argument error has several possible causes and, as a result, potential solutions. See our Error: ‘Bad Argument Type: Stringp Nil’ article to find your solution.

 Close

• Error: ‘Bad argument type: VLA-OBJECT nil’

A bad argument type error containing the text VLA-object nil means the software is expecting something in your drawing to be a «smart» object, but a variable in the code has caused that thing to not actually be an object. (In other words, it’s nil.) As a result, the software was not able to reference that object, which in turn prevented it from carrying out the action you were trying to complete and generated the error message.

As for the actual issue, it will depend on what you were trying to do when you received the error, as well as which object reference is now nil. Here are a few possible causes:

  • You have Local Data (MySQL), and your database connection object is nil

First, make absolute sure that you’ve followed our steps for what to do first when you see a bad argument type error – especially Step 3: Check for a bug in the code. Take note of exactly what you did (or tried to do) that resulted in the error, and check it against our recent updates, as described in those steps. 

If you can rule out a bug in the software based on those steps, your next step should be to diagnose a possible problem with your MySQL database server – but only if you’re using our software with a local (MySQL) database. Ask your IT administrator to troubleshoot your office’s MySQL database server, as described on our slow Land F/X performance troubleshooting article. Don’t know whether you’re using Local Data? Your CAD manager or IT admin can let you know.

  • You attempted to create a colorized plan using our Color Render tool 

In this case, the problematic object is a Truecolor object. If you’re getting this error every time you try to apply plant color, you can repair the error by following our steps to uninstall and reinstall AutoCAD or F/X CAD.

  • An XML file is damaged or missing

Are you getting this error right when opening CAD? Is CAD freezing up and you’re unable to use our software? If so, a file named _install_.xml, stored in your LandFX folder, is likely damaged or missing.

In this case, follow our steps to restore the install.xml file.

  • You attempted to perform one of several possible actions with a detail

Finally, you might receive this error when working with a detail. For example, you may have tried to edit, save, copy, or place a detail when you received the error.

In this case, the system is unable to read or write in that detail’s XML file. This can occur for several possible reasons:

  • You don’t have read/write permissions for the folder where that XML file lives. Have your IT administrator ensure that you have all the proper permissions to work with your office’s details. 
  • Your details are stored at a UNC path, which we don’t recommend. Ask your IT administrator to ensure that the folder containing your details is mapped to a letter drive.
  • Any number of issues with your Windows installation – another potential set of troubleshooting steps for your IT admin to complete.
  • Malware (less common). Your IT administrator should ensure that your computer and network are free of malware.

If you’ve ruled out all of the causes listed above, it’s likely that the XML file is missing from the location where the detail is stored. If so, copy the detail to your desktop and use our Save Detail tool to save it into the system.

Still getting the error? If you’ve ruled out permissions, a UNC path, your Windows installation, and malware, it’s possible that you or someone in your office has attempted to import the detail into a Land F/X project but clicked on the wrong XML file.  

Specifically, this error is the result of importing the file _index_.xml rather than the correct XML file for the detail you intended to import.

Instead, you need to import the XML file from the corresponding exported detail. Open the Detail Explorer and click Import.

You’ll then be prompted to select a detail export file.

Navigate to the location where you’ve exported the detail.

Open that folder, and select the file details.xml. Click Open.

You should now be able to work with that detail without receiving the error.

 Close

• Error: ‘Bad argument type: lentityp nil’

A bad argument type error containing the text lentityp nil can have several possible causes, including:

  • Drawing corruption (most commonly), or a bug in the software code

Make absolute certain that you’ve followed our steps for what to do first when you see a bad argument type error. Those steps include instructions on how to check for corruption in your drawing and how to check for a bug in the software.

Note that drawing corruption is the most common cause of this error. If you detect drawing corruption when completing the «what to do first» steps, follow our steps to clean your drawing and all Xrefs. We always recommend cleaning every single drawing you receive from someone else before you start working on it. Keeping your drawings clean will prevent a host of issues (including this error) and save you tons of time.

  • Locked layers in a drawing that contains callouts

If you’ve ruled out a bug and drawing corruption, the error is likely the result of locked layers that are preventing you from working with callouts in your drawing. These can include:

  • Plant labels
  • Reference Notes (RefNotes) 
  • Detail callouts
  • Valve callouts

To unlock layers in your drawing, see our lock/unlock layers documentation section. Note: We don’t recommend locking layers in your drawings – except those that contain your Xrefs.

At the very least, unlock all layers that contain callouts (or portions of callouts). You should now be able to continue working without seeing the error message.

 Close

• Error: ‘Bad argument type: VLA-object collection, VLA-object’

An error message containing the text ‘Bad argument type: vla-object collection’ is always the result of the software attempting (and failing) to determine which sheet you are working on. You might receive this error when:

  • Setting the drawing scale
  • Working with details or detail callouts
  • Doing anything that requires the software to know which sheet you are working on

Follow our steps to resolve this specific error.

 Close

• Sys-error: ‘Bad argument type: 2D/3D point: nil’

You’ll most commonly see this error when trying place or copy an object, or carry out a similar type of action, using one of our tools. You’re seeing the error because the system is unable to calculate an intersection in your drawing. Specifically, it’s trying (and failing) to calculate the distance between the cursor and the object you’re trying to place, copy, or verify. (We’ve seen it happen with placing plants or irrigation equipment such as valves, or using tools such as our Plant Mirror tool that copy objects in a drawing.)

Here’s a past example of this error message:

 [3.33] (sys-error «bad argument type: 2D/3D point: nil»)

:ERROR-BREAK.28 nil
[4.25] (ANGLE (907.216 795.06 0.0) nil)
[5.19] (C:VALVECALLOUT)

In this example, the user tried to place a valve callout but was unsuccessful because the system was unable to calculate the angle between the cursor and valve that was being called out. (Note that the issue can affect any number of items, from irrigation to plant labeling, site objects, etc.) 

This error most commonly results from:

• Corruption in your drawing

Drawing corruption is by far the most common cause of this error. Your first step should be to follow our instructions to clean the drawing and all Xrefs.

Cleaning your drawing will often take care of the error.

Still seeing the error after cleaning your drawing? Read on.

A bad argument type error containing the text 2D/3D point: nil can also result from:

• A bug in the software code

Make absolute sure you’ve followed our steps for what to do first when you see a bad argument type error – especially Step 3: Check for a bug in the code. Take note of exactly what you did (or tried to do) that resulted in the error, and check it against our recent updates, as described in those steps.

• Working in Paper Space rather than Model Space

Check whether you are working in Paper Space. If so, open the Model tab and work in Model Space. Try the same action that generated the error, but in Model Space. If you don’t see the error, you’ve resolved the issue.

You might also see this error if you’re labeling in a Paper Space viewport with the intention that the labels will be moved to Paper Space. If so, the error is occurring because of a problem with either the viewport or the User Coordinate System (UCS) you’re currently using.

Try labeling in a different Paper Space viewport. If you don’t see the error, you’ve isolated the problem to the other viewport.

• A problem with the current User Coordinate System (UCS)

The UCS you’re currently using for your drawing may have an issue that’s preventing the software from calculating angles between the cursor and objects in your plan. To check for and resolve this issue:

  • Use our Restore UCS tool to return your drawing to the World Coordinate System (WCS). Then try the action that generated the error (such as placing a valve callout).

    • Don’t see the error when attempting the same action in the WCS? If not, use our New UCS tool to set a new UCS for your drawing. Make sure you use our New UCS tool – not the AutoCAD UCS command.
    • Does the error persist in the WCS? If so, make absolute sure you’re working in Model Space and not Paper Space.

• An object with a Z elevation

You might see this error when clicking on an object that mistakenly has a Z elevation set to it. For example, you may be trying to call out a plant or a valve with a Z elevation.

Select the object you clicked.

Then open the Properties panel by typing Prop in the Command line and pressing Enter.

In the Properties panel, check the Position Z entry. If it’s anything other than 0, set it to 0. (If it’s already at 0, the object does not have a Z elevation.)

If you changed the Z elevation to 0, try the action that generated the error. Are you able to click the object without getting the error? You’ve solved the issue.

• Attempting to click objects on a locked layer

You might be trying to select an object on a locked layer. For example, you may be trying to call out a plant or valve whose layer is locked. See our section on locked and unlocked layers for instructions on how to unlock layers.

We generally don’t recommend locking layers – except those that contain your Xrefs.

• Using our Verify Labels tool when one of the blocks in your plan is empty – that is, no linework or objects inside the block

In this case, check the Command line history for the name of the object that caused the error. Check the Land F/X object data to determine which block is assigned. Then use one of the following possible solution options:

Option 1: Edit the data to use a different block that isn’t empty.

Option 2: Fix the empty block by either:

  • Using our Using our REDEFINEBLOCK tool, or
  • Editing the block manually to add linework inside it

Option 3: If using Reference Notes (RefNotes), consider whether the reason for the empty block is that you don’t actually want the block to be visible in your drawing.

If you don’t in fact want the block to be visible, change the RefNote from an Amenity RefNote to a Notation RefNote. Then use the Quick Select command to select and delete all the empty blocks and place Notation callouts instead.

 Close

• Error: ‘Bad argument type: consp nil’

This error can result from:

  • A bug in the software code

Make absolute sure you’ve followed our steps for what to do first when you see a bad argument type error – especially Step 3: Check for a bug in the code. Take note of exactly what you did (or tried to do) that resulted in the error, and check it against our recent updates, as described in those steps.

  • Attempting to select an item in your plan that is no longer in the current Land F/X project 

Once you’ve ruled out a bug, it’s time to check whether an object you’re attempting to select, such as a plant or a piece of irrigation equipment, has been removed from your project. If so, you’ll need to add that item back to your project.

  • A font issue

Did you get this error when trying to place text? Solution >

  • Update didn’t complete

Did you get this error after trying to run an update? The update may not have completed correctly. Follow our steps to Revert to a previous version after an update. Then run the update again and restart your computer.

 Close

• Error: ‘Bad argument type: INT nil’

We’ve seen this error pop up right after clicking the Site Color palette, but you might see it when you select or use other Land F/X tools as welll.

You can resolve this error quickly by following our steps to install the latest OpenDCL library.

 Close

I run into a problem in AutoCAD trying to get a VLA-OBJECT property like this with AutoLISP/ActiveX:

(vla-get-linetypes (vla-get-activedocument (vlax-get-acad-object)))

The error:

; error: bad argument type: VLA-OBJECT nil

Accessing other properties also failed.

Reinstall of AutoCAD was needed to solve the problem. Repair did not help.

Динамические блоки стали очень полезными элементами современного Автокада. Широкое применение динамических блоков значительно ускоряет процесс проектирования.

В этом уроке мы рассмотрим, как можно вставлять динамический блок и присваивать значения его атрибутам из LISP-программы. Для этого нам понадобятся материалы прошлых уроков. 

Вначале мы создадим блоки куба с дополнительными данными при помощи программы, рассмотренной нами в уроке: «LISP. Создание блока».

Скачать программу Mp_kub3.lsp Скачать программу Mp_kub3.lsp (Размер файла: 993 bytes)

Затем извлечем из блока дополнительные данные.

Вставим динамический блок, созданный нами в уроке: «Создание динамического блока», и внесем в него дополнительные данные из блока куба.

Скачать динамический блок Скачать динамический блок (Размер файла: 30 kB)

И так приступим:

Запустите AutoCAD.

Откройте Редактор Visual LISP, набрав в командной строке VLIDE (или VLISP)

Откройте программу mp_kub3, созданную в уроке: «LISP. Создание блока». См. Рис. 1

LISP. Динамический блок.

Рис. 1.   Программа mp_kub3.

Нажимаем кнопку «Загрузить активное окно редактора».

Затем на кнопку «Активизация AutoCAD».

Вводим в командной строке: mp_kub3 и нажмите <Enter>.

На запрос «Задайте длину стороны куба :» введите 300 и нажмите <Enter>

На запрос «Укажите базовую точку :» щелкните мышкой в рабочем окне Автокад.

Программа создаст блок куба с размерами сторон 300.

Повторно запустите программу (нажмите <Enter>).

На запрос «Задайте длину стороны куба :» введите 400 и нажмите <Enter>

На запрос «Укажите базовую точку :» щелкните мышкой в рабочем окне Автокад.

Программа создаст блок куба с размерами сторон 400.

В результате получим два куба, один со сторонами 300, другой 400. См. Рис. 2.

LISP. Динамический блок.

Рис. 2.   Создание блоков.

Вернемся в Редактор Visual LISP.

Создадим новый файл. Сохраним его под именем Udim.lsp.

Добавим в него строку для работы с функциями, входящими в расширение языка AutoLISP.

(vl-load-com)  - загружает функции расширения

Далее при помощи функции entsel попросим пользователя выбрать блок:

(entsel "Выберите блок: ")

Функция entsel возвращает имя указанного блока и координату точки указания.

При помощи функции car оставляем, только имя указанного блока:

(car (entsel "Выберите блок: "))

Функция car извлекает первый элемент из списка.

При помощи функции setq сохраняем имя блока в переменной obj:

(setq obj (car (entsel "Выберите блок: ")))

Далее преобразуем выбранный блок в vla-объект:

(setq vla_obj (vlax-ename->vla-object obj))

Имя vla-объекта сохраняем в переменной vla_obj.

Теперь мы можем извлечь дополнительные данные, которые ранее добавляли к блоку.

Для этого используем функцию vlax-ldata-get:

(setq V (vlax-ldata-get vla_obj "obem")) – извлекает данные 
из VLA-объекта vla_obj по коду "obem", и сохраняет их в переменной V.
(setq po (vlax-ldata-get vla_obj "tochka")) – извлекает данные 
из VLA-объекта vla_obj по коду "tochka", и сохраняет их в переменной po.

Выделите весь текст и нажмите на кнопку «Загрузить выделенный фрагмент». См. Рис. 3.

LISP. Динамический блок.

Рис. 3.   Извлекаем данные из VLA-объекта.

На запрос «Выберите блок :» — укажите один из двух блоков.

Чтобы посмотреть значения переменных.

Выделите переменную V и нажмите на кнопку «Добавить контрольное значение».

Затем, выделите переменную ро и снова нажмите на кнопку «Добавить контрольное значение». Откроется окно «Контрольное значение», где можно посмотреть, чему равны переменные. См. Рис. 4.

LISP. Динамический блок.

Рис. 4.  Значения переменных.

Мы видим, что нам удалось получить данные, которые ранние мы добавляли в блок.

Давайте еще извлечем имя блока.

При помощи функции entget получим список с характеристиками примитива (блока).

Откройте консоль Visual LISP.

Добавьте строку (entget obj).

Выделите ее и нажмите на кнопку «Загрузить выделенный фрагмент». См. Рис. 5.

LISP. Динамический блок.

Рис. 5.  Характеристики примитива.

Функция вернет список:

((-1 . <Имя объекта: 7ed146c8>) (0 . «INSERT») (5 . «251») (102 . «{ACAD_XDICTIONARY») (360 . < Имя объекта: 7ed146d0>) (102 . «}») (330 . < Имя объекта: 7ed12cf8>) (100 . «AcDbEntity») (67 . 0) (410 . «Model») (8 . «0») (100 . «AcDbBlockReference») (2 . «kub400») (10 1485.09 652.573 0.0) (41 . 1.0) (42 . 1.0) (43 . 1.0) (50 . 0.0) (70 . 0) (71 . 0) (44 . 0.0) (45 . 0.0) (210 0.0 0.0 1.0))

Из этого списка нам нужно извлечь имя блока. Мы видим, что DXF-код имени блока = 2.

Используем для этого функцию assoc .

Функция assoc применяется к сложному списку, каждый элемент которого начинается с DXF-кода. Именно по этому коду функция assoc и извлекает элемент из списка.

(assoc 2 (entget obj))
2  - DXF-код имени блока.
(entget obj) — список с данными блока.

Их списка будет извлечен элемент DXF-кодом 2:

Функция вернет следующее значение:

(2 . "kub400")

Чтобы оставить только имя блока, применим функцию cdr.

(cdr (assoc 2 (entget obj)))

Функция cdr – возвращает список без первого элемента.

Сохраним имя блока в переменной bl_name.

(setq bl_name (cdr (assoc 2 (entget obj))))

Добавьте эту строку, выделите ее, загрузите выделенный фрагмент. В окне консоль Visual LISP появится возвращаемое значение – имя блока. См. Рис. 6.

LISP. Динамический блок.

Рис. 6.   Извлекаем имя блока.

Все необходимые данные мы получили, теперь можно вставлять наш динамический блок Vyn.

Я напомню, что предыдущем уроке («Создание динамического блока») мы сохранили его в папке MyLisp: (D:MyLispVyn.dwg).

Если эта папка добавлена у Вас в пути поддержки Автокад. В программе достаточно использовать имя блока “Vyn”.

Если нет, то нужно использовать полный путь к файлу

“D:MyLispVyn.dwg”.

Как добавить папку в пути поддержки Автокад, показано в уроке «Пример программы LISP с диалоговым окном».

Вставляем динамический блок:

(command "_insert" "Vyn" po 1 1 0 bl_name V)
"_insert" – стандартная команда Автокад вставки блока;
"Vyn" – имя вставляемого блока;
(Если папка, в которой находится блок не прописана вспомогательных путях Автокад,
в качестве имя нужно указать полный путь к файлу “D:MyLispVyn.dwg”)
рo – базовая точка вставки блока;
1 – масштабный коэффициент по оси X;
1 – масштабный коэффициент по оси Y;
0 – угол поворота блока в радианах;
bl_name – значение верхнего атрибута;
V – значение нижнего атрибута;

Добавляем эту строчку и преобразуем нашу программу в пользовательскую функцию defun

(defun c:Udum (/)
      <наша программа>
) ; end_defun

В результате получим. См.Рис. 7.

LISP. Динамический блок.

Рис. 7.  Вставляем динамический блок.

Загружаем активное окно редактора.

Переходим в Автокад.

В командной строке вводим Udim и нажимаем <Enter>.

На запрос «Выберите блок :» — укажите один из двух блоков.

Повторите команду (нажмите <Enter>).

На запрос «Выберите блок :» — укажите второй блок.

Программа построит две выноски. См. Рис. 8.

LISP. Динамический блок.

Рис. 8.  Текстовые выноски.

Мы видим, что у блока kub300 базовая точка не попала в цент верхней грани. Это произошло потому, что в момент вставки блока сработала привязка «середина отрезка». Поэтому когда вставляется блок привязки нужно отключить:

(setq osm (getvar "osmode")) – запоминаем привязки пользователя
(setvar "osmode" 0) – отключаем привязки

     Вставляем блок.

(setvar "osmode" osm) – возвращаем привязки пользователя.

Кроме этого давайте сделаем так, чтобы наша программа бесконечное количество раз просила выбрать блок, до тех пор, пока мы сами не прервем ее нажав <Esc>.

Для этого, добавим бесконечный цикл.

(while Т
      <выражения>
) :end while.

(более подробно об этом рассказано в уроке: «Пример AutoLISP программы: Сумма длин отрезков»)

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

; ошибка: неверный тип аргумента: lentityp nil

Поэтому добавляем условие, которое будет проверять, чтобы переменная obj не равнялась nil.

(if (not (= obj nil))
   (progn
      <наши выражения>
   ) ;end progn
) ; end if

(более подробно об этом рассказано в уроке: «Пример AutoLISP программы: Сумма длин отрезков»)

В результате получим см. рис. 9.

LISP. Динамический блок.

Рис. 9.  Добавляем строчки.

Проверяем работу программы.

Удаляем динамические блоки.

Загружаем активное окно редактора.

Переходим в Автокад.

В командной строке вводим Udim и нажимаем <Enter>.

На запрос «Выберите блок :» — специально пощелкайте мимо блока. Программа не прерывается. Укажите один блок.

На следующий запрос «Выберите блок :» — выберите второй блок.

На следующий запрос – нажмите <Esc>.

Программа построит две выноски. См. Рис. 10

LISP. Динамический блок.

Рис. 10.   Выноски.

Мы видим, что полки у динамических блоков немного коротковаты. К тому же полку у блока kub400 не помешало бы немного поднять. Поскольку это динамические блоки, мы без особого труда можем сделать это вручную, но все таки хочется, чтобы это делала программа. Этим мы займемся в следующем уроке.

В заключение добавляем  локальные переменные в список временных переменных функции defun. См. Рис. 11.

LISP. Динамический блок.

Рис. 11.    Добавляем локальные переменные.

Код программы:

(defun c:Udim (/ obj vla_obj V po bl_name osm)
     (vl-load-com)  ; загружаем функции расширения 
     (while T 
          (setq obj (car (entsel "nВыберите блок: ")))
          (if (not (= obj nil)) 
               (progn
                    (setq vla_obj (vlax-ename->vla-object obj))  ; переводим в vla-object 
                    (setq V (vlax-ldata-get vla_obj "obem"))      ; объем 
                    (setq po (vlax-ldata-get vla_obj "tochka"))   ; координаты центра 
                    (setq bl_name (cdr (assoc 2 (entget obj)))) ; имя блока

                    (setq osm (getvar "osmode"))                    ; запоминаем привязки пользователя 
                    (setvar "osmode" 0)                                  ; отключаем привязки 
                    (command "_insert" "Vyn" po 1 1 0 bl_name V)  ; вставка блока 
                    (setvar "osmode" osm)    ; возвращает привязки пользователя 
               );end progn 
          ); end if 
     ); end while
 ); end_defun

Скачать программу Udim.lsp Скачать программу Udim.lsp (Размер файла: 538 bytes)

На этом наш урок окончен.

В следующем уроке мы рассмотрим, как из LISP-программы изменять геометрические характеристики динамического блока.

Пишите в комментариях:

Трудно ли было выполнить этот урок?

Была ли для Вас полезной информация, данная в этом уроке?

На какие вопросы программирования, Вы хотели бы, увидит ответы в следующих уроках?

Я с удовольствием отвечу на ваши вопросы.

Если вы хотите получать новости с моего сайта. Оформляйте подписку.

До новых встреч.

 «Автор: Михаил Орлов»

Google

Также на эту тему Вы можете почитать:

  • Ошибка неверный номер телефона счета договора
  • Ошибка неверный тип аргумента safearrayp nil
  • Ошибка неверный номер платежа
  • Ошибка неверный тип аргумента or stringp symbolp nil
  • Ошибка неверный код пятерочка