An Introduction to AutoLISP

download An Introduction to AutoLISP

of 194

Transcript of An Introduction to AutoLISP

  • 7/31/2019 An Introduction to AutoLISP

    1/194

  • 7/31/2019 An Introduction to AutoLISP

    2/194

    expertos. Muchas de las funciones agregadas al programa LISP para interfaz lenguajes

    directamente a AutoCAD y ver que se han conservado algunos comandos de AutoCAD como

    funciones de lenguajes.

    AutoLISP is an 'interpreted' language rather than a 'compiled' language, which means each program statementis translated and evaluated as the program is read into the computer. This differs from a compiled language

    for which a complete translation into machine code is made prior to a program 'execution' step.Program statements in AutoLISP are sets of functions and other data that are used with the function containedwithin parentheses. An example of such a function and its other data is:Lenguajes es un lenguaje "interpretado" en lugar de un lenguaje "compilado", que significa cada

    instruccin del programa es traducido y evalu que el programa se lee en el equipo. Esto difiere de

    un lenguaje compilado para que se hizo una traduccin completa a cdigo mquina antes a un

    paso de 'ejecucin' del programa. Las declaraciones de programa en lenguajes son conjuntos de

    funciones y otros datos que se utilizan con la funcin figuran entre parntesis. Un ejemplo de tal

    funcin y sus otros datos es:

    (command "line" pt1 pt2 pt3 pt4 "close")

    Here, the function is 'command', which precedes the familiar AutoCAD 'line' command and its sub-command'close'. The content of the parentheses is a self-contained statement which causes a line to be drawn betweenthe four points pt1 through pt4, and back to pt1. You must have already defined the meaning of the fourpoints so that AutoCAD can use them to draw the lines.Aqu, la funcin es 'comando', que precede el comando de 'lnea' familiar de AutoCAD y su sub-

    command 'cerrar'. El contenido de los parntesis es una declaracin independiente que provoca

    una lnea entre los cuatro pt1 de puntos a travs de pt4 y volver a pt1. Debe ya ha definido el

    significado de los cuatro puntos para que AutoCAD puede utilizarlos para dibujar las lneas.

    AUTOLISP DATA TYPES.Functions such as 'command', are termed 'built-in' or 'internal' functions. They are also known as subroutines,or simply 'subrs'. The subroutine terminology will be more familiar to those of you who have programmed in

    other languages such as FORTRAN. The 'other data' that appear with the function are called the 'arguments'of the function.TIPOS DE DATOS DE LENGUAJES. Se denominan funciones tales como 'comando', 'integrado' o

    'interior' funciones. Son tambin conocidos como subrutinas, o simplemente 'subrs'. La

    terminologa de la subrutina ser ms familiar para aquellos de ustedes que han programado en

    otros lenguajes como FORTRAN. Los 'otros datos' que aparecen con la funcin son llamados los

    'argumentos' de la funcin.

    Page 1 of 64

    An Introduction to AutoLISP. Some AutoLISP functions (subrs) require that arguments be supplied in aparticular order, and others may include optional arguments, or no arguments at all. The complete set of

    functions is listed in the AutoLISP Programmer's Reference, published by Autodesk, Inc., and supplied topurchasers of AutoCAD.Introduccin a lenguajes. Algunas funciones de lenguajes (subrs) requieren que se suministran argumentos enun orden determinado, y otros pueden incluir argumentos opcionales o sin argumentos a todos. El conjuntocompleto de funciones es enumerado en referencia del programador de lenguajes, publicado por Autodesk,Inc. y suministra a los compradores de AutoCAD.The data types that AutoLISP recognizes are:Functions (subroutines, subrs).Examples are +, -, *, \, command, princ, setq.

  • 7/31/2019 An Introduction to AutoLISP

    3/194

    (note that the arithmetic operators are treated as functions by AutoLISP)Arguments of the functions.Examples are variables (also known as symbols).constants (real (decimal) or integer).character strings.file names (descriptors).AutoCAD entity names.AutoCAD selection sets.external functions (supplied by the AutoCAD Development System).AutoLISP data is supplied in the form of lists, where the items of the list can themselves be lists. For instance,in our example of the command function.Los tipos de datos que reconoce lenguajes son: funciones (subrutinas, subrs). Algunos ejemplos son +, -, *, \,comando, princ, setq. (tenga en cuenta que los operadores aritmticos son tratados como funciones delenguajes) Argumentos de las funciones. Algunos ejemplos son variables (tambin conocido comosmbolos). constantes (real (decimal) o entero). cadenas de caracteres. nombres de archivo (descriptores).Nombres de entidades de AutoCAD. Conjuntos de seleccin de AutoCAD. funciones externas(proporcionadas por el sistema de desarrollo de AutoCAD). Datos de lenguajes se suministran en forma delistas, donde los elementos de la lista pueden ser listas. Por ejemplo, en nuestro ejemplo de la funcin decomando.(command "line" pt1 pt2 pt3 pt4 "close")

    the seven items contained in the parentheses form a list. Four of these items are the variables (symbols) pt1through pt4 representing AutoCAD points. Now, since the points contain x, y and z coordinates, they are alsolists. The other two arguments, "line" and "close" are examples of character strings.los siete elementos contenidos en los parntesis forman una lista. Cuatro de estos elementos son la pt1 devariables (smbolos) a travs de pt4 que representan puntos de AutoCAD. Ahora, ya que contienen los puntosx, y y z coordenadas, tambin estn listas. Los otros dos argumentos, "lnea" y "cerrar" son ejemplos decadenas de caracteres.AutoLISP Atoms.A single item of a list, which is not itself a list, is called an 'atom' in AutoLISP terminology. According to thisdefinition, atoms are the fundamental indivisible particles of AutoLISP. Atoms are individual elements suchas symbols, numbers and subrs, and a complete set of the atoms can be displayed on your screens by entering!atomlist at the AutoCAD command prompt. We will discuss the atomlist more fully later in this series.tomos de lenguajes. Un solo elemento de una lista, que no es una lista, se llama un 'tomo' en la

    terminologa de lenguajes. De acuerdo con esta definicin, los tomos son las partculas fundamentalesindivisibles de lenguajes. Los tomos son elementos individuales, como smbolos, nmeros y subrs, y unconjunto completo de los tomos se puede mostrar en sus pantallas introduciendo! atomlist en la lnea decomandos de AutoCAD. Analizaremos el atomlist ms detalle ms adelante en esta serie.EXECUTING AUTOLISP.AutoLISP input can be entered by typing in expressions in an AutoCAD session (at the command prompt), byreading in the expressions from an ASCII file, or by reading from a string variable which may represent acomplete program.LA EJECUCIN DE LENGUAJES. Entrada de lenguajes puede introducirse escribiendo en expresiones enuna sesin de AutoCAD (en la lnea de comandos), lectura en las expresiones de un archivo ASCII, o por lalectura de una variable de cadena que puede representar un programa completo.Execution by typing in an AutoLISP expression.Try typing in the following at the AutoCAD command prompt:Ejecucin escribiendo en una expresin de lenguajes. Intente escribir en el siguiente en el smbolo deAutoCAD:(command "line" "2,3" "4,5" " 6,3" "close")Don't forget to include the parentheses, or AutoCAD won't recognize that this is an AutoLISP expression!Your AutoCAD screen should now display a triangle. In this case, the variables used for points have beenreplaced by character strings enclosed by double quotation marks. Now erase the triangle and re-type theexpression with "c" replacing the "close" element. The result is the same, because the command functionallows regular AutoCAD commands and subcommands to be entered.No olvide incluir los parntesis o AutoCAD no reconoce que este es una expresin de lenguajes! La pantallade AutoCAD ahora debe mostrar un tringulo. En este caso, las variables utilizadas para puntos han sido

  • 7/31/2019 An Introduction to AutoLISP

    4/194

    reemplazadas por cadenas de caracteres entre comillas dobles. Ahora borrar el tringulo y vuelva a escribir laexpresin con "c" reemplazar el elemento de "cerrar". El resultado es el mismo, porque la funcin decomando permite regulares comandos de AutoCAD y subcomandos para introducirse.Execution by reading an expression from an ASCII file.Now, shell out of AutoCAD and create an ASCII file (this can be done with EDLIN or the DOS 5 EDIT texteditor) named PROG1.LSP that contains only the above AutoLISP expression. To execute your firstAutoLISP program, erase the previous triangle, then use the following LOAD function at the commandprompt:Ejecucin mediante la lectura de una expresin de un archivo ASCII. Ahora, shell de AutoCAD y crear unarchivo ASCII (esto puede hacerse con EDLIN o el editor de texto DOS 5 EDIT) llamado PROG1.LSP quecontiene slo la expresin anterior de lenguajes. Para ejecutar su primer programa de lenguajes, borrar eltringulo anterior y, a continuacin, utilice la siguiente funcin de carga en la lnea de comandos:Command: (load "prog1")again, don't forget the parentheses and the double quotes, and you should see the triangle as before. Note herethat the program executes and draws the triangle immediately on being loaded, and this is generally true forAutoLISP programs that contain only subrs (built-in functions).una vez ms, no olvides los parntesis y las comillas dobles, y debera ver el tringulo como antes. Sealaraqu que el programa se ejecuta y dibuja el tringulo inmediatamente de ser cargado, y esto sucedegeneralmente en programas de lenguajes que contienen slo subrs (funciones).Page 2 of 64

    An Introduction to AutoLISP AutoLISP execution from a file containing defined functions.In addition to subrs, it is also possible to define your own functions for AutoLISP. Such functions are calleddefined functions to distinguish them from the built-in functions. If a program contains a defined function,when the program is loaded, the name of the defined function must also be entered in parentheses so that itcan be executed.Una introduccin a los lenguajes lenguajes ejecucin de un archivo que contiene define funciones. Ademsde subrs, tambin es posible definir sus propias funciones para lenguajes. Estas funciones se denominanfunciones definidas para distinguirlos de las funciones integradas. Si un programa contiene una funcindefinida, cuando se carga el programa, el nombre de la funcin definida tambin se indicarn entre parntesispor lo que se puede ejecutar.Try this by changing your prog1.lsp file to read the following:Intente esto modificando el archivo prog1.lsp para leer lo siguiente:

    (defun test1 ()(command "line" "6,3" "8,5" "10,3" "c"))Don't forget to include all the parentheses. The AutoLISP subr to define functions is (defun .....), and in thiscase the name of the defined function is test1. Now, if the AutoLISP file is named prog1.lsp, the followingsequence is followed:No olvide incluir todos los parntesis. La subr lenguajes para definir funciones es (defun...) y en este caso elnombre de la funcin definida es Prueba1. Ahora, si el archivo de lenguajes se denomina prog1.lsp, sigue lasiguiente secuencia:Command: (load "prog1")TEST1Command: (test1)Here, the word TEST1 appears immediately when the program is loaded by the first statement, but the

    program is not executed until you enter '(test1)', the name of the defined function. We will see more of thedefun function later, and the significance of the empty pair of parentheses will be made clear in the section on'global and local variables'.Aqu, la palabra que Prueba1 aparece inmediatamente cuando se carga el programa por la primera instruccin,pero el programa no se ejecuta hasta que escriba '(Prueba1)', el nombre de la funcin definida. Ms de lafuncin defun veremos ms adelante, y la importancia del par de parntesis vaco se har claro en la seccin"variables locales y globales".AutoLISP execution with 'C:'

  • 7/31/2019 An Introduction to AutoLISP

    5/194

    If the AutoLISP defined function name begins with C:, then after loading the program, the defined functionbecomes a regular AutoCAD command that can be executed like other AutoCAD commands at the commandprompt by entering its name without parentheses. Try editing the prog1.lsp file to read:Si el nombre de la funcin definida de lenguajes empieza con C:, entonces despus de cargar el programa, seconvierte la funcin definida en un comando de AutoCAD regular que se puede ejecutar como otroscomandos de AutoCAD en la lnea de comandos escribiendo su nombre sin parntesis. Intente editar elarchivo prog1.lsp para leer:(defun C:TEST1 ()(command "line" "6,3" "8,5" "10,3" "c"))then use the following sequence of commands:a continuacin, utilice la siguiente secuencia de comandos:Command: (load "prog1")C:TEST1Command: test1The name C:TEST1 is automatically written by AutoCAD when the program is loaded. At this point, the newcommand 'test1' may be entered at any time. An AutoLISP program containing one or more 'defun' definedfunctions only needs to be loaded once in any drawing session.La C:TEST1 de nombre automticamente es escrito por AutoCAD cuando se cargue el programa. En estepunto, el nuevo comando 'Prueba1' pueden escribirse en cualquier momento. Un programa de lenguajes que

    contiene uno o ms 'defun' funciones definidas slo necesita ser cargado una vez en cualquier sesin dedibujo.AutoLISP execution from menu macros.AutoLISP expressions can be contained in menu macros to be executed when the menu label is selected. Ifyou examine the AutoCAD release 11 menu file ACAD.MNU, you will notice that it contains manyAutoLISP programs and expressions.Ejecucin de lenguajes de macros del men. Pueden contener expresiones de lenguajes de macros del menque se ejecutar cuando se selecciona la etiqueta de men. Si examina el archivo de AutoCAD versin 11men ACAD.MNU, observar que contiene muchos programas de lenguajes y expresiones.I use a personal menu file that I can select from a modified form of the standard ACAD.MNU. A menu itemof the form [aux-menu]^C^Cmenu;aux; is placed at a convenient position (I use the 'File' POP menu) in thestandard menu, then I place a similar command in my 'AUX.MNU' file to allow easy return to the standardmenu. My preference is to leave the standard menu alone, except for this small change so that the regular

    AutoCAD menus are always available on demand, and any new material is then placed into the aux.mnumenu.Utilizar un archivo de men personal puedo seleccione de una forma modificada de la ACAD. estndarMNU.Un elemento de men del formulario [aux-men] ^ C ^ Cmenu; aux; se coloca en una posicin cmoda (usarel men 'Archivo' POP) en el men estndar, a continuacin, colocar un comando similar en mi 'auxiliarMNU' archivo para permitir fcil retorno al men estndar. Mi preferencia es dejar el men estndarsolo, excepto para esta pequea modificacin para que los mens de AutoCAD regulares siempre estndisponibles en la demanda, y cualquier material nuevo, a continuacin, se coloca en el men aux.mnu.Here is a sample of my new POP2 menu which you can use for a basic AutoLISP development environment:Aqu es una muestra de mi nuevo men POP2 que puede utilizar para un entorno de desarrollo bsico delenguajes:***POP2[Set-ups]||[Lisp program development]^C^C$p2=p22 $p2=*||**p22Page 3 of 64

    An Introduction to AutoLISP [Set-ups]Una introduccin a los lenguajes [configuraciones]

  • 7/31/2019 An Introduction to AutoLISP

    6/194

    [Edit-LSP]^C^Cshell ed C:/acad11/lisp/test.lsp;graphscr[Test-LSP]^C^C(load "/acad11/lisp/test");(test);[Print test.lsp]^C^C(load "/acad11/lisp/printest");(printest);[~--]|In the above, when the POP2 menu 'Set-ups' is selected, one of the choices is 'Lisp program development', andthis displays a new page that includes items to edit a file named test.lsp in the subdirectory lisp which iscontained in the AutoCAD directory, acad11. The call to the editor in this case is ed, because that is the nameof the editor I use. You may substitute edlin or edit or the name of your favorite text editor (provided that itproduces ASCII output) in place of this.Anteriormente, cuando se selecciona el men POP2 'Configuraciones', una de las opciones es 'Desarrollo delprograma Lisp', y esto muestra una nueva pgina que incluye elementos para editar un archivo llamadotest.lsp en el lisp subdirectorio que figura en el directorio de AutoCAD, acad11. La llamada al editor en estecaso es ed, porque ese es el nombre del editor de que uso. Puede sustituir edlin o edit o el nombre de su editorde textos preferido (siempre que produce la salida de ASCII) en lugar de esto.This menu macro only edits the file called test.lsp, which is the name I give to the current LISP program that Iam developing. To edit any other file, most text editors allow you to choose the filename after the editor hasbeen entered, so you could simply leave out the filename until the editor is running. Edlin requires a filenameto be supplied on execution, so simply give the shell command and issue the edlin command from theoperating system.

    Esta macro de men slo edita el archivo llamado test.lsp, que es el nombre que tiene el actual programa deLISP que estoy desarrollando. Para editar cualquier otro archivo, muchos editores de texto le permiten elegirel nombre del archivo despus de haberse introducido el editor, por lo que simplemente podra dejar salir elnombre del archivo hasta que se ejecuta el editor. Edlin requiere un nombre de archivo a suministrarse enejecucin, as que simplemente dar el comando shell y emitir el comando edlin desde el sistema operativo.The use of separate directories for lisp programs is a good management procedure that I recommend. Afterthe lisp file has been created or edited, it can be immediately tested by the Test-LSP macro, which loads andexecutes test.lsp assuming a defined function named 'test' has been created.The 'Print test.lsp' option calls a LISP program that prints the test.lsp file. The AutoLISP program to do thishas been adapted from the Autodesk Inc. 'Fprint.lsp' program, which is freely available to you formodification (with the appropriate acknowledgements to Autodesk). We will examine this program in detaillater in the course. In the meantime, you may use your text editor or the DOS print command to print yourprogram.

    El uso de directorios separados para programas lisp es un procedimiento de buena gestin que recomiendo.Despus de que el archivo lisp ha sido creado o editado, se puede probar inmediatamente por la macro pruebaLSP, que carga y ejecuta test.lsp suponiendo que se ha creado una funcin definida denominada 'probar'. Laopcin de 'Imprimir test.lsp' pide un programa LISP que imprime el archivo test.lsp. El programa de lenguajespara ello ha sido adaptado de la 'Fprint.lsp' de Autodesk Inc. programa, que se encuentra librementedisponible para su modificacin (con los reconocimientos adecuados a Autodesk). Examinaremos esteprograma en detalle ms adelante en el curso. Entretanto, puede utilizar el editor de texto o comando paraimprimir su programa de impresin de los DOS.GLOBAL AND LOCAL VARIABLES.The default mode of AutoLISP is to define all variables to be 'global', which means that the variables aregenerally available not only when the program containing them is executed, but also after the execution iscompleted. This means that other programs you write will have access to variables that were defined byprevious programs. It is possible to see the values of global variables by typing their names preceded by ! atthe command prompt. For instance, if pt1 is a variable that represents a point whose coordinates are2.5,3.0,0.0, then typing !pt1 will display the three coordinate values.VARIABLES LOCALES Y GLOBALES. El modo predeterminado de lenguajes es definir todas lasvariables a ser "global", que significa que todas las variables estn generalmente disponibles no slo cuandoel programa que las contiene es ejecutado, sino tambin una vez finalizada la ejecucin. Esto significa queotros programas que escribes tendrn acceso a las variables que fueron definidas por los programas anteriores.Es posible ver los valores de las variables globales escribiendo sus nombres precedidos por! en el smbolo delsistema. Por ejemplo, si pt1 es una variable que representa un punto cuyas coordenadas son 2.5,3.0,0.0, luegoescribir! pt1 mostrar los tres valores de coordenadas.

  • 7/31/2019 An Introduction to AutoLISP

    7/194

    Global variables appear in the ATOMLIST, and take up memory in the computer. For these reasons, andbecause you will probably not want variables such as PT1 to take values left over by previous programs, it iswise not to have global variables hanging around at the end of execution.In order to avoid global variables, you may declare the program variables to be 'local' to a particular definedfunction by adding their names, preceded by a slash mark and a space (/ ) in the parentheses which aresupplied for that purpose in the defun statement, thus:Las variables globales aparecen en el ATOMLIST y ocupan memoria en el equipo. Por estas razones, porqueprobablemente no querr variables como PT1 a tomar valores de izquierda por los programas anteriores, esaconsejable no tener variables globales rondando al final de la ejecucin. A fin de evitar las variablesglobales, puede declarar las variables de programa a ser 'local' para una determinada funcin definidaagregando sus nombres, precedidos por un signo de barra diagonal y un espacio (/) en el parntesis que sesuministran para ello en la declaracin de defun, as:(defun test2 (/ pt1 pt2 pt3 pt4)...........)will make all of the point variables local. Note here that other variables may be defined as arguments of thedefun function, appearing before the slash mark, for instance,har que todas las variables de punto local. Nota aqu que otras variables pueden definirse como argumentosde la funcin defun, que aparece antes del signo de barra diagonal, por ejemplo,(defun test3 (a b / pt1 pt2 pt3 pt4).............)means that the two arguments a and b must be supplied to the defined function test3 before it can be executed,and instead of executing with (test3) as before, you must supply values, such as (test3 2.2 3.0) so that the

    variables a and b can take any value you wish, in this case, 2.2 and 3.0 respectively. We will see examples ofprograms using global and local variables in the next lesson in this series.significa que los dos argumentos una y b debe suministrarse a la funcin definida sector3 antes de que sepuede ejecutar, y en lugar de ejecutar con (sector3) como antes, debe suministrar valores, tales como (sector32.2 3.0) para que las variables una y b puede tener cualquier valor que se desea, en este caso, 2.2 y 3.0respectivamente. Vamos a ver algunos ejemplos de programas usando variables globales y locales en lasiguiente leccin en esta serie.Home work questions:

    1. Why are the closing parentheses in the last 2 defined function examples on the same line as theopening parentheses, instead of on a separate line as in our previous defined function examples?

    2. Are the arguments a and b in the last defined function example local or global variables?

    Trabajo a domicilio preguntas: 1. por qu son los parntesis de cierre en los ltimos 2 ejemplos defuncin definida en la misma lnea que el parntesis de apertura, en lugar de en una lneaindependiente como en los ejemplos anteriores de funcin definida? 2. Son los argumentos de unay b en las ltimas funcin definida ejemplo local o global variables?

    Page 4 of 64

    An Introduction to AutoLISP

    3. How would you draw circles and arcs with AutoLISP expressions? Use the 'command' function todraw a circle with the '2-POINT' method, with the points at absolute coordinates 3,4 and 6,4respectively. Test this on your computer at the AutoCAD command prompt.

    4. Using only the functions 'defun' and 'command', write a program to define a function which draws atriangle and a circumscribing circle (through the vertices of the triangle). Make the 3 points of thetriangle at 3,4; 6,4; and 5,6 in x,y locations respectively.

    3. Cmo se dibuja crculos y arcos con expresiones de lenguajes? Utilice la funcin de 'comando'

    para dibujar un crculo con el 2-punto ' mtodo, con los puntos en absoluto coordina 3,4 y 6,4

    respectivamente. Esta prueba en el equipo en la lnea de comandos de AutoCAD. 4. Utilizando

    slo las funciones 'defun' y 'comando', escribir un programa para definir una funcin que dibuja un

  • 7/31/2019 An Introduction to AutoLISP

    8/194

    tringulo y un circunscribir un crculo (a travs de los vrtices del tringulo). Hacer los 3 puntos del

    tringulo en 3,4; 6,4; y 5,6 en x, y lugares respectivamente.

    In lesson two of this series, "AutoLISP program evaluation and control", you will learn the formats ofAutoLISP functions and arguments, with examples of argument types. Alternative programming methods fornesting functions are covered with examples of how to make your programs clear and easy to read. You will

    also learn how and when AutoLISP evaluates expressions, and how you can control the evaluation by usingspecial 'quote' functions and other special characters. Finally, you will see how the basic assignment functionallows you to create variables in your programs.En la leccin dos de esta serie, "control y evaluacin de programas de lenguajes", aprender los

    formatos de las funciones de lenguajes y argumentos, con ejemplos de tipos de argumentos.

    Mtodos de programacin alternativos para anidar funciones estn cubiertos con ejemplos de

    cmo hacer sus programas claros y fciles de leer. Tambin aprender cmo y cundo lenguajes

    evala las expresiones y cmo se puede controlar la evaluacin mediante funciones especiales

    'presupuesto' y otros caracteres especiales. Por ltimo, ver cmo la funcin de asignacin bsica

    permite crear variables en sus programas.

    Page 5 of 64

    An Introduction to AutoLISP AutoLISP program evaluation andcontrol

    Lesson Two in the CADalyst University of Wisconsin Introduction to AutoLISP Programming coursecovers function formats, parenthesis control and basic error checking.

    by Anthony Hotchkiss, Ph.D, P.Eng.About this course.Introduction to AutoLISP Programming is an eight-lesson independent study course, originally published inmonthly installments in CADalyst magazine. Readers may optionally register for the course in order toreceive a copy of the printed course outline, a study guide containing additional AutoLISP examples,reference materials, and solutions to the practical assignments. On successfully completing an intermediate

    and a final mail-in project, students will receive certificates of completion and 4.0 CEU's (continuingeducation units).Acerca de este curso. Introduccin a los lenguajes de programacin es un curso de ocho horas de estudioindependiente, publicado originalmente en cuotas mensuales en la revista CADalyst. Los lectoresopcionalmente pueden registrarse para el curso a fin de recibir una copia del esquema impreso del curso, unagua de estudio que contiene ejemplos de lenguajes, materiales de referencia y soluciones para lasasignaciones de prcticas adicionales. Por completar satisfactoriamente un intermediario y un proyecto decorreo final, los estudiantes recibirn certificados de finalizacin y 4.0 CEU (unidades de educacincontinua).For further information, contact:Steve Bialek Engineering Professional Development University of Wisconsin-Madison 432 North Lake StreetMadison, Wisconsin 53706 (608) 262-1735article.

    LESSON TWO - AUTOLISP PROGRAM EVALUATION AND CONTROL.This months lesson shows you how to write some simple AutoLISP programs. Special text characters areintroduced, and the format of the AutoLISP functions and arguments is explained, with examples of argumenttypes. Alternative programming methods for nesting functions are covered with examples of how to makeyour programs clear and easy to read. You will see how the basic assignment function allows you to createand use variables in your programs. You will also learn how and when AutoLISP evaluates expressions, andhow you can control the evaluation by using special 'quote' functions and other special characters.LECCIN DOS - LENGUAJES PROGRAMA EVALUACIN Y CONTROL. Esta leccin de meses lemuestra cmo escribir algunos programas de lenguajes simples. Especial se introducen caracteres de texto y elformato de las funciones de lenguajes y argumentos se explica, con ejemplos de tipos de argumentos.

  • 7/31/2019 An Introduction to AutoLISP

    9/194

    Mtodos de programacin alternativos para anidar funciones estn cubiertos con ejemplos de cmo hacer susprogramas claros y fciles de leer. Ver cmo la funcin de asignacin bsica le permite crear y usar variablesen sus programas. Tambin aprender cmo y cundo lenguajes evala las expresiones y cmo se puedecontrolar la evaluacin mediante funciones especiales 'presupuesto' y otros caracteres especiales.Programs are controlled by parentheses rather than by lines, and you will see examples of the correct use ofparentheses and double quotes. Many errors are caused by not closing quotes and parentheses, and this lessonwill show you how to check for these and some other errors. We will show some example programs toillustrate these ideas, and the lesson ends with some homework questions to test your understanding of thetext.Programas estn controlados por parntesis, en lugar de hacerlo por las lneas, y se ver ejemplos del usocorrecto de los parntesis y comillas dobles. Muchos errores son causados por no cerrar comillas y parntesis,y esta leccin le mostrar cmo comprobar estos y algunos otros errores. Vamos a mostrar algunos programasde ejemplo para ilustrar estas ideas, y la leccin termina con algunas preguntas de deberes para probar sucomprensin del texto.SPECIAL CHARACTERS FOR PROGRAMMING.You already know that AutoCAD menus use special characters like the semi-colon (;) or a blank space for'return', and the carat (^) symbol for the 'control' key. AutoLISP uses the following special characters inprogram statements:CARACTERES ESPECIALES PARA LA PROGRAMACIN. Ya saben que los mens de AutoCADutilizan caracteres especiales como el punto y coma (;) o un espacio en blanco para 'volver' y el smbolo de

    quilates (^) para la tecla 'control'. Lenguajes utilizan los siguientes caracteres especiales de instrucciones deprograma:

    \n means newline\n significa nueva lnea\r means return\" means the character "\t means tab\e means escape\\means the character \\nnn means the character whose octal code is nnn\nnn significa el carcter cuyo cdigo octal es nnn' means the quote function"significa que la funcin de oferta

    ; precedes comments in a program (until the end of the current line); precede a comentarios en un programa (hasta el final de la lnea actual)" means the start and end of a literal string of characters"significa el comienzo y el final de una cadena de caracteres literal. A dot preceded by a space is reserved for designating 'dotted-pairs'. Un punto precedido por un espacio est reservado para la designacin de 'puntos pares'The back-slash character (\) is used as a control character for whatever follows it in a 'literal string' ofcharacters. A literal string of characters means that the characters are merely text, not to be confused withsymbols (variables). LiteralSe utiliza el carcter de barra de la parte posterior (\) como un carcter de control para lo que sigue en unacadena literal de caracteres. Una cadena literal de caracteres significa que los personajes son simplementetexto, no debe ser confundido con smbolos (variables). LiteralPage 6 of 64An Introduction to AutoLISP

  • 7/31/2019 An Introduction to AutoLISP

    10/194

    Literal strings are contained within double quotes ("). For example, consider the 'prompt' function which isused to display messages when AutoLISP is executing:las cadenas Literales estn contenidas dentro de comillas dobles ("). Por ejemplo, considere la funcinde 'smbolo' que se utiliza para mostrar mensajes durante la ejecucin de lenguajes:(prompt "\nWelcome to AutoLISP")This statement has the effect of starting a new line (because of the \n character), followed by the display of thewords 'Welcome to AutoLISP'. The double quotes indicate that the individual words, welcome, to, andAutoLISP, are not variables that can represent values, but are simply text characters to be displayed in thecommand area of your AutoCAD screen.Esta declaracin tiene el efecto de iniciar una nueva lnea (por el carcter \n), seguida de la visualizacin delas palabras "Bienvenido a lenguajes". Las comillas dobles indican que las palabras individuales, Bienvenido,y lenguajes, no son variables que pueden representar valores, sino simplemente caracteres de texto que semostrar en el rea de comandos de la pantalla de AutoCAD.Try the following examples at your AutoCAD command prompt, but use the spacebar instead of the 'enter' or'return' key:Pruebe los siguientes ejemplos en la lnea de comandos de AutoCAD, pero utilice la barra espaciadora enlugar de la tecla 'Intro' o 'retorno':(prompt "This is AutoLISP") (prompt "\nThis is AutoLISP")The results should look like the following:Los resultados deben tener el siguiente aspecto:

    Command: (prompt "This is AutoLISP") This is AutoLISPnilCommand:and:Command: (prompt "\nThis is AutoLISP")This is AutoLISPnilCommand:In the first case, the character string is written on the same line, and in the second case a new line precedes themessage. In both cases, note that the word 'nil' appears after the message. This is because the AutoLISPfunction 'prompt' produces (or 'returns') a value of 'nil', and we will see how to deal with this unwanted textlater in the series when we consider the 'print' functions.En el primer caso, la cadena de caracteres se escribe en la misma lnea, y en el segundo caso, una nueva lneaprecede el mensaje. En ambos casos, tenga en cuenta que la palabra 'cero' aparece despus del mensaje. Estoes porque la funcin de lenguajes 'smbolo' produce (o 'devuelve') un valor de 'cero', y ya veremos cmo lidiar

    con este texto no deseado ms adelante en la serie cuando consideramos las funciones 'imprimir'.Note also that in these examples, the spacebar was used to enter the LISP statements. What would havehappened if you had used the 'enter' key instead? Try it!Tenga en cuenta tambin que en estos ejemplos, la barra espaciadora se utiliza para introducir lasdeclaraciones de LISP. Qu habra sucedido si hubiera utilizado la tecla 'Intro' en su lugar? Prubalo!You can see that using special characters like \ and " can help in writing character strings to the screen, butwhat if you want to use these control characters as part of the text string itself? That is why the characters \\and \" appear in the list of special characters. It is possible that you may want to refer to DOS pathnames, inwhich case the back-slash character would be part of the name. An example isSe puede ver que mediante caracteres especiales como \ y "pueden ayudar a escribir cadenas de caracteres enla pantalla, pero lo que si desea utilizar estos caracteres de control como parte de la propia cadena de texto?Por eso los personajes \\ y \ "aparecen en la lista de caracteres especiales. Es posible que desee hacerreferencia a DOS rutas, en cuyo caso el carcter de barra de espalda sera parte del nombre. Un ejemplo es..."\acad\lisp\myfile.lsp"...which would have to be written asque tendra que ser escrita como..."\\acad\\lisp\\myfile.lsp"...We will discuss the subject of file handling in lesson six of this series, and the other special characters will beintroduced in appropriate places later in this series.Analizaremos al tema de la manipulacin en leccin seis de esta serie de archivos, y los otros caracteresespeciales se introducirn en lugares apropiados posteriormente en esta serie.AUTOLISP FUNCTION FORMATS AND ARGUMENTS.

  • 7/31/2019 An Introduction to AutoLISP

    11/194

    Functions, also known as subroutines, or simply 'subrs' are subject to some rules and restrictions. The subrsmust be contained within parentheses, and the function name must immediately follow the open parenthesis.The 'arguments' of the function (discussed in lesson one), contain the required data for the function.Some AutoLISP functions (subrs) require that arguments be supplied in a particular order, and others mayinclude optional arguments, or no arguments at all. The number of arguments depend on the actual functionbeing used.FORMATOS DE FUNCIN DE LENGUAJES Y ARGUMENTOS. Funciones, tambin conocido comosubrutinas, o simplemente 'subrs' estn sujetas a algunas restricciones y reglas. El subrs debe estar contenidadentro de parntesis, y el nombre de la funcin debe seguir inmediatamente el parntesis de apertura. Los'argumentos' de la funcin (comentado en la leccin uno), contienen los datos necesarios para la funcin.Algunas funciones de lenguajes (subrs) requieren que se suministran argumentos en un orden determinado, yotros pueden incluir argumentos opcionales o sin argumentos a todos. El nmero de argumentos depende de lafuncin real que se utiliza.Functions are evaluated by AutoLISP, and they return certain values, or, as we have seen in the case of the'prompt' function, they may return 'nil'. For example, consider the following functions:(terpri) means 'terminate printing', is equivalent to a 'newline', and requires no arguments. This functionreturns 'nil'.Funciones son evaluadas por lenguajes y regresan ciertos valores, o, como hemos visto en el caso de lafuncin de 'smbolo', regresan 'cero'. Por ejemplo, considere las siguientes funciones: (terpri) significa'terminar la impresin', es equivalente a una lnea nueva y no requiere argumentos. Esta funcin devuelve

    'cero'.(sin angle) requires one argument (an angle value in radians), and returns the sine of the angle(* number number number .....) may have any number of arguments, and returns the product of all thenumbers. This is the multiplication function.(ngulo de pecado) requiere un argumento (un valor de ngulo en radianes) y devuelve el seno de un ngulo(* nmero nmero nmero.....) puede tener cualquier nmero de argumentos y devuelve el producto de todoslos nmeros. sta es la funcin de multiplicacin(setq var1 expr1 var2 expr2 .....) is the basic assignment function which can have any number of pairs ofvariables and expressions. This function assigns the content of the nth expression to the nth variable, andreturns the value of the last expression in the list.(setq var1 var2 expr1 expr2.....) es la funcin de asignacin bsica que puede tener cualquier nmero de paresde variables y expresiones. Esta funcin asigna el contenido de la expresin n a la variable n-sima ydevuelve el valor de la ltima expresin de la lista.

    Page 7 of 64

    An Introduction to AutoLISP(defun name (variable list) Function_definition_statements) the first argument is the name of the definedfunction, the variable list may be empty or may be any number of global and local variables (see lesson one).An unlimited number of Function_definition_statements can be included, and defun returns the name of thefunction.(defun nombre (lista de variables) Function_definition_statements) el primer argumento es el nombre de lafuncin definida, la lista de variable puede estar vaca o puede ser cualquier nmero de variables globales ylocales (vase leccin uno). Puede incluirse un nmero ilimitado de Function_definition_statements y defundevuelve el nombre de la funcin.NESTING OF FUNCTIONS.Controlling the program sequence with parentheses allows you to 'nest' parentheses inside each other, so that

    LISP functions can exist inside other functions. The following example will show the many different ways inwhich a result can be obtained to a programming problem.ANIDAMIENTO DE FUNCIONES. Controlar la secuencia de programa con parntesis permite 'nido'parntesis dentro de otras, para que funciones LISP pueden existir dentro de otras funciones. En el ejemplosiguiente se muestran las diferentes maneras en que puede obtenerse un resultado a un problema deprogramacin.Suppose we want to evaluate the formulaSupongamos que queremos evaluar la frmulaX = -b + ( ( ((b**2)-4ac)**(.5) )/2a )for the case where

  • 7/31/2019 An Introduction to AutoLISP

    12/194

    a = 1.5b = 2.0c = 0.5we could use the following set of functions:podramos utilizar el siguiente conjunto de funciones:(setq a 1.5)(setq b 2.0)(setq c 0.5)Here, we use the basic AutoLISP assignment function setq, in which only one variable and one expression isset for each 'setq' function. We can then continue with some nested functions where the multiplicationfunction is included in the setq function:Aqu usamos bsico lenguajes asignacin funcin setq, en el que se establece slo una variable y unaexpresin para cada funcin de 'setq'. A continuacin, podemos continuar con algunas funciones anidadasdonde se incluye la funcin de multiplicacin en la funcin setq:(setq b2 (* b b))(setq ac4 (* 4 a c))(setq a2 (* a 2))Next, we can subtract the values under the square-root sign by setting a new variable 'd':A continuacin, nos podemos restar los valores bajo el signo de raz cuadrada estableciendo una nuevavariable sera ':

    (setq d (- b2 ac4))Now we introduce the square root function 'sqrt', and set another new variable 'e':Ahora introducimos la funcin raz cuadrada 'raiz' y establecer otra nueva variable 'e':(setq e (sqrt d))We can continue with the following, setting another new variable 'f':Podemos continuar con el siguiente, estableciendo otro nuevo variable 'f':(setq f (/ e a2))(setq x (- f b))Our final program looks like:Aspecto nuestro programa final:(setq a 1.5)(setq b 2.0)(setq c 0.5)

    (setq b2 (* b b))(setq ac4 (* 4 a c))(setq a2 (* a 2))(setq d (- b2 ac4))(setq e (sqrt d))(setq f (/ e a2))(setq x (- f b))Note how the multiplication, division and subtraction functions are nested inside of the assignment function.This program is simply a collection of AutoLISP functions, and will execute immediately on loading with(load "filename"), where 'filename' is the name of the file ending in the file extension .lsp, as covered inlesson one of this series.Observe cmo las multiplicacin, divisin y resta funciones anidadas dentro de la funcin de asignacin. Esteprograma es simplemente un conjunto de funciones de lenguajes y se ejecutar inmediatamente en carga con(carga "filename"), donde 'nombre_archivo' es el nombre del archivo que termina en el .lsp de extensin dearchivo, como cubierto en una leccin de esta serie.Now, because the format for setq allows us to group together any number of pairs of variables andexpressions, this program could be written as:Ahora, porque el formato de setq nos permite agrupar cualquier nmero de pares de variables y expresiones,este programa podra escribirse como:(setq a 1.5Page 8 of 64

    An Introduction to AutoLISP

  • 7/31/2019 An Introduction to AutoLISP

    13/194

    b 2.0c 0.5b2 (* b b)ac4 (* 4 a c)a2 (* a 2)d (- b2 ac4)e (sqrt d)f (/ e a2)x (- f b)Which is clearer because fewer parentheses are used and it is obvious which variables and expressions belongto each other.Que es ms claro porque se utilizan parntesis menos y es obvio que las variables y expresiones pertenecenmutuamente.This could be written in the much less pleasing form:Esto podra ser escrito en forma mucho menos agradable:(setq a 1.5 b 2.0 c 0.5 b2 (* b b) ac4 (* 4 a c) a2 (* a 2) d ( - b2 ac4) e (sqrt d) f (/ e a2) x (- f b))Another possibility is to use a nesting approach in order to set the value of x directly as in:Otra posibilidad es utilizar un enfoque de anidacin a fin de establecer el valor de x directamente en:(setq a 1.5b 2.0

    c 0.5)(setq x (- (/ (sqrt (- (* b b) (* 4 a c))) (* a 2)) b))Note that for every open parenthesis there must exist a closing parenthesis, and the evaluation of the programis controlled by the placement of the parentheses. These examples illustrate that programs can be made simpleand readable, or complex and unreadable, and it is not usually worthwhile saving lines of code by makingyour programs unnecessarily complicated. The last example eliminates the need to invent new variables, butis somewhat difficult to check. However, it does have a certain readability which is closer in form to theoriginal equation than the other examples.Observe que para cada parntesis de apertura debe existir un parntesis de cierre, y la evaluacin delprograma est controlada por la colocacin de los parntesis. Estos ejemplos ilustran que pueden hacerseprogramas simple y legible, o complejo y no se puede leer, y no vale la pena suele ahorrar lneas de cdigohaciendo sus programas innecesariamente complicados. El ltimo ejemplo elimina la necesidad de inventarnuevas variables, pero es algo difcil de comprobar. Sin embargo, tiene una cierta legibilidad que est ms

    cerca en forma de la ecuacin original que los otros ejemplos.AN AUTOLISP PROGRAM TO DRAW A BOX.AutoCAD draws points. lines, arcs and plines, but not boxes. Here we give a very simple program to draw asquare box of any size. Variables are assigned in two ways: by using the setq function, and provided as anargument to the defined function. You will also see some new subrs and their usage.The following program is annotated by using comments. Comments begin with a semi-colon, and continueuntil the end of the line on which they appear.UN PROGRAMA DE LENGUAJES PARA DIBUJAR UN CUADRO. AutoCAD dibuja puntos. lneas,arcos y plines, pero no de cajas. Aqu damos un programa muy simple para dibujar un cuadrado de cualquiertamao. Variables se asignan de dos maneras: mediante la funcin setq y siempre como un argumento a lafuncin definida. Tambin ver algunos nuevos subrs y su uso. El siguiente programa es anotado mediante eluso de comentarios. Los comentarios comienzan con un punto y coma y continan hasta el final de la lnea enla que aparecen.; BOX1.LSP, a program to draw a square with origin and length of a side.1.LSP, un programa para dibujar un cuadrado con el origen y la longitud de un lado.;(defun box1 (len) ; The variable 'len' means the length of side

    La variable 'len' significa la longitud del lado(setq pt1 (getpoint "\nEnter the origin point: ") ; The 'getpoint' functionpt2 (polar pt1 0.0 len) ; Polar requires an angle in radians

    Polar requiere un ngulo en radianespt3 (polar pt2 (/ pi 2.0) len) ; 'pi' is built in to AutoLISP

    'pi' es incorporado en lenguajes

  • 7/31/2019 An Introduction to AutoLISP

    14/194

    pt4 (polar pt3 pi len) ; polar, base-point, angle, distance; polar, punto de base, ngulo, distancia

    ) ; End of setting variables for points; Fin de establecer variables para puntos(command "line" pt1 pt2 pt3 pt4 "c") ; Drawing the box) ; End of the 'defun'To execute this program, use:Para ejecutar este programa, utilice:(load "box1")(box1nnn)where nnn is the length of side of the box, and will be substituted for the 'len' variable.Note that when a variable such as 'len' is supplied as an argument to the defined function, you can not makethe defined function a command by naming it with the C: prefix.donde nnn es la longitud del lado del cuadro y ser sustituida por la variable 'len'. Tenga en cuenta quecuando se suministra una variable como 'len' como argumento a la funcin definida, no se puede hacer lafuncin definida por un comando por nombrar con el prefijo C:.When this program executes, you will be prompted to select the lower-left corner of the box by the prompt"Enter the origin point : ". You may pick a position with the cursor, (using an osnap mode or grid and snap ifdesired) or enter the coordinates of the point via the keyboard in regular AutoCAD format, as though youwere supplying the from or to points of a line. The box will then be drawn automatically. You can draw as

    many boxes as you like, after the program has been loaded, by using the (box1 nnn) format.Cuando se ejecuta este programa, se le pedir que seleccione la esquina inferior izquierda del cuadro de por elindicador "Introduzca el punto de origen:". Puede elegir una posicin con el cursor (utilizando un modo deosnap o cuadrcula y ajustar si lo desea) o introduzca las coordenadas del punto mediante el teclado enformato de AutoCAD regular, como si se suministra la desde o hacia los puntos de una lnea. El cuadro acontinuacin, se dibujar automticamente. Puede dibujar tantas casillas como desee, despus de que se hacargado el programa, mediante el formato (1 nnn).Page 9 of 64

    An Introduction to AutoLISPThe new functions introduced here are 'getpoint' and 'polar'. The syntax for the getpoint function is:Las nuevas funciones introducidas aqu son 'getpoint' y 'polar'. La sintaxis de la funcin getpoint es:(getpoint base-point prompt-string)

    The base-point and prompt-string are optional arguments to this function. The getpoint function pauses foruser input of a point, and returns the point selected. If a prompt-string is supplied, it will be displayed asthough it were an AutoCAD prompt. If the optional base-point is supplied (this may be pre-defined as avariable, or may be given as a list of coordinates in the appropriate format), then AutoCAD draws a 'rubber-band' line from the base-point to the current cursor position.El punto de base y la cadena de mensaje son argumentos opcionales para esta funcin. La funcin getpoint sedetiene para entrada de usuario de un punto y devuelve el punto seleccionado. Si se proporciona una cadenade smbolo del sistema, se mostrar como si se tratara de un indicador de AutoCAD. Si se proporciona elpunto de base opcional (esto puede ser predefinida como una variable, o puede darse como una lista decoordenadas en el formato adecuado), a continuacin, AutoCAD dibuja una lnea de 'goma' desde el punto debase a la posicin actual del cursor.The format of a point in AutoLISP is a list of the coordinates of the point. After the box program hasexecuted, enter !pt1 at the command prompt, and you will see the list of coordinates for the point 'pt1'

    displayed as follows:El formato de un punto en lenguajes es una lista de las coordenadas del punto. Una vez que ha ejecutado elprograma de cuadro, introduzca! pt1 en el smbolo del sistema y usted ver la lista de coordenadas para elpunto de 'pt1' aparece como sigue:Command: !pt1(4.48057 7.35181 0.0)Command:Note that the value of pt1 (and any other of the point variables) can only be displayed here because they are'global' variables, and have been added to the atomlist. If these variables were defined to be local, by writingthe defined function as

  • 7/31/2019 An Introduction to AutoLISP

    15/194

    Tenga en cuenta que el valor de pt1 (y cualquier otra de las variables de punto) slo se puede mostrar aquporque son variables 'globales' y se han agregado a la atomlist. Si estas variables se definicin como local,escribiendo la funcin definida como(defun box1 (len / pt1 pt2 pt3 pt4)...............then entering !pt1 at the command prompt would display 'nil'.luego entrar! pt1 en el smbolo mostrara 'cero'.The polar function has the following argument list:La funcin polar tiene la lista de argumentos siguientes:(polar base-point radian-angle distance)There are no optional arguments, and the base-point and angle are with reference to the current usercoordinate system. The polar function returns a point as a list of real numbers contained in parentheses.No hay ningn argumento opcional, y el punto de base y el ngulo son con referencia al sistema decoordenadas de usuario actual. La funcin polar devuelve un punto como una lista de nmeros reales figuraentre parntesis.AUTOLISP EVALUATION AND QUOTED LISTS.The AutoLISP evaluator takes a line of input, evaluates it, and returns a result. A line of input begins with anopen parenthesis and ends with the matching closing parenthesis. Any nested lines of input are evaluated anda result is returned. Results cannot be returned until a matching closing parenthesis is found, and so theevaluation returns results for the innermost nested functions first.EVALUACIN DE LENGUAJES Y LISTAS ENTRE COMILLAS. El evaluador de lenguajes toma una

    lnea de entrada, evala y devuelve un resultado. Una lnea de entrada comienza con un parntesis de aperturay termina con el parntesis de cierre coincidentes. Se evalan las anidadas lneas de entrada y devuelve unresultado. No se puede devolver resultados hasta que se encuentre un parntesis de cierre coincidentes, y porlo que la evaluacin devuelve resultados de las ms ntimos funciones anidadas en primer lugar.Generally, variables evaluate to their current values, and constants, strings and subrs evaluate to themselves.Lists are evaluated according to the first element of the list, which is normally a subr or a defined function.The remaining elements in a list are taken as arguments of the list.Generalmente, variables de evaluacin a sus valores corrientes y constantes, cadenas y subrs evaluar a smismos. Las listas se evalan segn hasta el primer elemento de la lista, que normalmente es una subr o unafuncin definida. Los elementos restantes en una lista se toman como argumentos de la lista.Remember that a list is contained within parentheses, and the lists that we have seen so far have been eitherdefined functions or subrs (built-in functions). Now consider the following list:Recuerde que una lista figura entre parntesis, y las listas que hemos visto hasta el momento han sido

    funciones definidas o subrs (funciones). Ahora considere la siguiente lista:(command "line" pt1 pt2 pt3 pt4 "c")Here, the list has a subr as its first item, so the remaining elements are taken to be arguments of the subr. The'command' subr which we first encountered in lesson one, provides a method for submitting AutoCADcommands (in this case 'line'), subcommands ('c'), and 2D and 3D points (pt1 through pt4). The commandsand subcommands are actually strings (contained in double quotes), but let us examine the point variables.We have already seen that pt1 has the format (4.48057 7.35181 0.0) which is a list of three real numberswhich represent the x, y, z coordinates of a point.Aqu, la lista tiene un subr como su primer tema, por lo que los elementos restantes se considera que sonargumentos de la subr. La subr 'comando' que nos encontr por primera vez en la leccin uno, proporciona unmtodo para enviar AutoCAD comandos (en este caso 'lnea'), subcomandos ('c'), y puntos de 2D y 3D (pt1mediante pt4). Los comandos y los subcomandos son en realidad cadenas (figura entre comillas dobles), peroexaminemos las variables de punto. Ya hemos visto que pt1 tiene el formato (4.48057 7.35181 0,0) que es unalista de tres nmeros que representan la x, y, las coordenadas z de un punto.It appears that the list represented by pt1 is not compatible with the criterion for evaluation of lists givenabove, since the first element of the list is neither a defined function nor a subr. The same problem occurs inthe 'polar' list, which also uses the list of real numbers to represent the base-point. Clearly, we need a way ofexpressing lists which are not functions, and which are not evaluated.Parece que no es compatible con el criterio de evaluacin de listas dadas anteriormente, ya que el primerelemento de la lista es una funcin definida ni una subr la lista representada por pt1. El mismo problema seproduce en la lista 'polar', que tambin utiliza la lista de los nmeros reales para representar el punto de base.Claramente, necesitamos una forma de expresar que no son funciones, y que no se evalan las listasHow can we set the value of a point directly in the form (setq pt1 (2.0 3.0 0.0))? Try entering

  • 7/31/2019 An Introduction to AutoLISP

    16/194

  • 7/31/2019 An Introduction to AutoLISP

    17/194

    SOME BASIC ERROR CHECKING.If you don't match your closing parentheses with your open parentheses, AutoLISP displays a prompt of theform n> where n is the number of missing closing parentheses. The way to deal with this in the simplest caseis to enter the missing parentheses, such as ))) if n is 3, or alternatively enter Control-C (^C) to cancel.ALGUNOS COMPROBACIN DE ERRORES BSICOS. Si no coinciden con los parntesis de cierre con

    los parntesis abiertos, lenguajes muestra un indicador de la forma n > donde n es el nmero de

    desaparecidos entre parntesis de cierre. La manera de lidiar con esto en el caso ms sencillo esintroducir las faltantes parntesis, como))) si n es 3, o alternativamente escriba Control C (^ C)

    para cancelar.

    However, a common mistake is to leave out closing double quotes, in which case AutoLISP will interpret anyfollowing parentheses as text strings and the results of entering closing parentheses will be unpredictable. Ifthe error prompt is 3> and entering a single closing parenthesis does not reduce this to 2>, you can enter adouble quote followed by another closing parenthesis. Now the number should reduce, and you can repeat theprocess until the program finishes execution. It is extremely unlikely that a program with such errors willexecute properly, so you should edit the program and re-load and test it.Sin embargo, un error comn es dejar a cerrar comillas dobles, en cuyo caso lenguajes interpretar

    cualquier siguientes parntesis como cadenas de texto y los resultados de introducir parntesis de

    cierre ser impredecibles. Si el indicador de error es 3 > y entrar en un parntesis de cierre nico

    no reducir esto a 2 >, puede introducir una comilla doble seguido de otro parntesis de cierre.

    Ahora debera reducir el nmero y puede repetir el proceso hasta que el programa termine de

    ejecucin. Es extremadamente improbable que un programa con esos errores se ejecutar

    correctamente, por lo que debe modificar el programa y vuelva y probarlo.

    When you are writing your first programs, you can always test individual statements by entering them at thecommand prompt to make sure that they work before including them in your program (.lsp) file.It is always a good idea to ensure that your variables are being assigned correctly by checking their valueswith the ! character at the AutoCAD command prompt after a program has run, or during the development ofa program. You don't have to write a complete program in order to make some of these checks.

    Al escribir sus primeros programas, siempre puede probar las declaraciones individuales por entraren el smbolo del sistema para asegurarse de que funcionan antes de incluirlos en el archivo de

    programa (.lsp). Siempre es una buena idea para asegurar que las variables que se asignan

    correctamente comprobando sus valores con el! carcter en la lnea de comandos de AutoCAD

    despus de ejecuta un programa o durante el desarrollo de un programa. No tienes que escribir un

    programa completo para poder hacer algunos de estos controles.

    You can also 'comment out' any lines of your program by entering a semi-colon at the beginning of any line,but make sure that you always have matched parentheses at all times.Tambin puede 'comentario' las lneas de su programa introduciendo un punto y coma al principio

    de cualquier lnea, pero asegrese de que usted siempre ha igualado entre parntesis en todo

    momento.

    Home work assignments.1. Use the defun, setq, polar, getpoint, command and arithmetic functions (*, +, -, /) to write a program thatwill draw an "I" beam cross section as shown in figure HW1. Let the user supply the height H of the cross-section, and the origin point.2. How can you add fillets to your I-beam cross section?

  • 7/31/2019 An Introduction to AutoLISP

    18/194

    Asignaciones de trabajo a domicilio. 1. Utilice la defun, setq, polar, getpoint, funciones de

    comandos y aritmticas (*, +, -, /) para escribir un programa que sacar un "yo" viga transversal

    como se muestra en la figura HW1. Permitir que el usuario proporcione la altura h de la seccin

    transversal y el punto de origen. 2. Cmo puede agregar filetes a tu i transversal?

    3. How would you automatically dimension the "I" beam of question1? Add this feature to your program.Hint - use the command function for the appropriate dimension types and define extra points with setq inorder to specify the dimension locations.3. Cmo podra usted Acotacin automtica la "I" haz de Pregunta1? Agregar esta caracterstica a

    su programa. Sugerencia - utilizar la funcin de comando para los tipos de dimensin adecuada y

    definir puntos extras con setq para especificar las ubicaciones de dimensin.

    In lesson three of this series, "Manipulating lists with AutoLISP", you will learn more programmingtechniques and some new functions for manipulating lists. You will see how to use individual x, y or zcomponents of point lists and how to construct and append elements to lists. Example programs will illustratehow you can work with lists.En la leccin tres de esta serie, "Manipulacin listas con lenguajes", aprender ms tcnicas de

    programacin y algunas nuevas funciones para manipular listas. Ver cmo utilizar individuales x,y o z componentes de listas de punto y cmo construir y aadir elementos a las listas. Programas

    de ejemplo ilustran cmo se puede trabajar con listas.

    Page 11 of 64

    An Introduction to AutoLISP Manipulating lists with AutoLISP Lesson Three in theCADalyst/University of Wisconsin Introduction to AutoLISP Programming course shows you how to

    construct and work with lists. by Anthony Hotchkiss, Ph.D, P.Eng.About this course.Introduction to AutoLISP Programming is an eight-lesson independent study course, originally published inmonthly installments in CADalyst magazine. Readers may optionally register for the course in order toreceive a copy of the printed course outline, a study guide containing additional AutoLISP examples,

    reference materials, and solutions to the practical assignments. On successfully completing an intermediateand a final mail-in project, students will receive certificates of completion and 4.0 CEU's (continuingeducation units).For further information, contact:Steve Bialek Engineering Professional Development University of Wisconsin-Madison 432 North Lake StreetMadison, Wisconsin 53706 (608) 262-1735For further information, contact, see the enrollment form attached to this article.

    LESSON THREE - MANIPULATING LISTS WITH AUTOLISP.In this months lesson you will learn more programming techniques and some new functions for manipulatinglists. You will see how to use individual x, y or z components of point lists and how to construct and appendelements to lists. Example programs will illustrate how you can work with lists, and the lesson ends withsome homework questions to test your understanding of the text.

    LECCIN TRES - MANIPULAR LISTAS CON LENGUAJES. En esta leccin de meses aprender mstcnicas de programacin y algunas nuevas funciones para manipular listas. Ver cmo utilizar individuales x,y o z componentes de listas de punto y cmo construir y aadir elementos a las listas. Programas de ejemploilustran cmo se puede trabajar con listas, y la leccin termina con algunas preguntas de deberes para probarsu comprensin del texto.PROGRAM STRUCTURE AND REDUCING THE NUMBER OF VARIABLESIn lesson two we wrote a program to draw a square box, and here we will use that simple program as anillustration of how to reduce the number of variables used in a program. The BOX1.LSP program, uses thepoint variables pt1, pt2, pt3 and pt4, which are assigned and used later in the 'command line' function.

  • 7/31/2019 An Introduction to AutoLISP

    19/194

    ESTRUCTURA del programa y la reduccin del nmero de VARIABLES En la leccin dos escribimos unprograma para dibujar un cuadrado, y aqu vamos a utilizar ese programa simple como una ilustracin decmo reducir el nmero de variables utilizadas en un programa. 1.Programa LSP, utiliza el punto variablespt1 pt2, pt3 y pt4, asignado y utilizado ms adelante en la funcin de lnea de comando.; BOX1.LSP, a program to draw a square with origin and length of a side.1.LSP, un programa para dibujar un cuadrado con el origen y la longitud de un lado.; (defun box1 (len) ; The variable 'len' means the length of side

    La variable 'len' significa la longitud del lado(setq pt1 (getpoint "\nEnter the origin point: ") ; The 'getpoint'function pt2 (polar pt1 0.0 len) ; Polar requires an angle in radians

    Polar requiere un ngulo en radianespt3 (polar pt2 (/ pi 2.0) len) ;'pi' is built in to AutoLISP

    'pi' es incorporado en lenguajespt4 (polar pt3 pi len) ; polar, base-point, angle, distance

    ; polar, punto de base, ngulo, distancia) ; End of setting variables for points(command "line" pt1 pt2 pt3 pt4 "c") ; Drawing the box) ; End of the 'defun'It is possible to write this program using only one point variable as in the following listing:Es posible escribir este programa usando slo un punto variable como en el siguiente anuncio:

    ; BOX11.LSP, a program to draw a square with origin and length of a side.; BOX11.LSP, un programa para dibujar un cuadrado con el origen y la longitud de un lado.(defun box11 (len)(setq p (getpoint "\nEnter the origin point: "))(command "line" p(setq p (polar p 0.0 len))

    Page 12 of 64

    An Introduction to AutoLISP(setq p (polar p (/ pi 2.0) len))(setq p (polar p pi len)) "close")) ; End of the 'defun'

    Notice how the command function is used in this case. The point variable 'p' is defined initially by the'getpoint' function, but during the line command, the point is re-defined with reference to itself. Each of thesetq assignments returns the value of its expression (the new point definition), which is used as successiveinput to the AutoCAD line command.Observe cmo la funcin de comando se utiliza en este caso. Inicialmente se define la variable de punto 'p'por la funcin 'getpoint', pero durante la lnea de comandos, el punto es redefinirlos con referencia a s mismo.Cada una de las asignaciones de setq devuelve el valor de su expresin (la nueva definicin punto), que se usacomo entrada sucesiva a la lnea de comandos de AutoCAD.The getpoint function cannot be used inside the command function, and that is why we defined the first pointoutside of the command function before starting to draw the line. Note that the setq function returns the valueof its last expression, which means that the point assignments must be made with separate setq functions,rather than with a list of pairs of variables and expressions.No se puede utilizar la funcin getpoint dentro de la funcin de comando, y por eso hemos definido el primer

    punto fuera de la funcin de comando antes de empezar a dibujar la lnea. Tenga en cuenta que la funcin setqdevuelve el valor de su ltima expresin, lo que significa que las asignaciones de punto deben hacerse confunciones setq separado, en lugar de hacerlo con una lista de pares de variables y expresiones.Reducing the number of variables in your programs is a convenience, but there are times when you will needto retain separate point variables, especially if you want to use parametric programming with automaticdimensioning. The box programs are simple forms of parametric programs, although the only parameter is thelength of side of the box. If you want to dimension the box, you must have access to the points which weredefined at the corners of the box. For the square box, only one side need be dimensioned, but you will need todefine a point to specify the position of the dimension line.

  • 7/31/2019 An Introduction to AutoLISP

    20/194

    Reducir el nmero de variables en sus programas es una conveniencia, pero hay veces que cuando necesitarmantener variables de punto aparte, especialmente si desea utilizar programacin paramtrica con Acotacinautomtica. Los programas de cuadro son formas simples de programas paramtricos, aunque el nicoparmetro es la longitud del lado del cuadro. Si desea que el cuadro de cota, debe tener acceso a los puntosque fueron definidos en las esquinas del cuadro. Para el cuadro, slo un lado necesita ser dimensionado, perotendr que definir un punto para especificar la posicin de la lnea de cota.Let's suppose that you want to use a vertical dimension on the right-hand side of the box, with the verticaldimension line 0.75 inches from the box, as shown in figure 3.1. You will need to use a program of the formof our BOX1.LSP above, with an extra point, pt5, defined to be at 0.75 inches from point 2 (pt2), so the line:Supongamos que desea utilizar una dimensin vertical en el lado derecho del cuadro, con la lnea dedimensin vertical 0,75 pulgadas en el cuadro, como se muestra en la figura 3.1. Necesitar utilizar unprograma de la forma de nuestros 1.LSP arriba, con un punto extra, pt5, definido como 0,75 pulgadas en elpunto 2 (pt2), por lo que la lnea:(setq pt5 (polar pt2 0.0 0.75))should be added. The program would then include the command function for dimensioning, such as:debe aadirse. El programa incluira entonces la funcin de comando para la acotacin, tales como:(command "dim1" "ver" pt2 pt3 pt5 "")We used the form DIM1 here, so that the dimension mode would automatically terminate after placing thesingle dimension. Note that there is no such command as 'linear' for dimensions, and the subcommand "ver"was used directly after the "dim1" command. The rest of the sequence defines the endpoints of the side of the

    box and the position of the dimension line, followed by a return (2 double quotes) to accept the dimensioncalculated by AutoCAD. The final program, which produced the box of figure 3.1, would look like:Hemos utilizado el formulario DIM1 aqu, por lo que el modo de dimensin concluira automticamentedespus de colocar la dimensin nica. Observe que no hay ningn comando tal como 'lineal' para lasdimensiones, y se utiliz el subcomando "ver" directamente despus del comando "dim1". El resto de lasecuencia define los extremos de la parte del cuadro y la posicin de la lnea de cota, seguida de un retorno (2comillas dobles) para aceptar la dimensin calculada por AutoCAD. El programa definitivo, que produjo elcuadro de la figura 3.1, quedara como:; BOX31.LSP, a program to draw and dimension a square with origin: and length of a side.; BOX31.LSP, un programa para dibujar y acotar un cuadrado con origen: y la longitud de un lado.; (defun box31 (len) ; The variable 'len' means the length of side

    ; La variable 'len' significa la longitud del lado

    (setq pt1 (getpoint "\nEnter the origin point: ") ; The 'getpoint'function pt2 (polar pt1 0.0 len) requires an angle in radians; Polar pt3 (polar pt2 (/ pi 2.0) len) ;'pi' is built in to AutoLISP

    ;'PI' es incorporado en lenguajespt4 (polar pt3 pi len) ; polar, base-point, angle, distance

    polar, punto de base, ngulo, distancia) ; End of setting variables for points(command "line" pt1 pt2 pt3 pt4 "c") ; Drawing the box;; Dimensioning the box;(setq pt5 (polar pt2 0.0 0.75)) ; Setting the dimension line position

    ; Establecer la posicin de la lnea de cota(command "dim1" "ver" pt2 pt3 pt5 "")) ; End of the 'defun'MANIPULATING LISTSThe functions for creating and manipulating lists areLas funciones para crear y manipular listas sonPage 13 of 64

    An Introduction to AutoLISP(list expr1 expr2 expr3.....) (cons item list)(car list) (cdr list) (cadr list) (caar list) (caddr list) (cadar list) ...

  • 7/31/2019 An Introduction to AutoLISP

    21/194

    (length list) (listp item)(last list) (nth integer list)(append list1 list2) (member expr list) (reverse list)The functions list and cons are used to create lists, and the other functions manipulate and return informationabout the lists.La lista de funciones y contras se utilizan para crear listas, y las otras funciones de manipulan y devolucininformacin acerca de las listas.List can have any number of expressions, and it returns the list of all of the expressions in sequence. Forinstance, (list 4.5 3.5 0.0) returns the list (4.5 3.5 0.0). The statementLista puede tener cualquier nmero de expresiones y devuelve la lista de todas las expresiones en secuencia.Por ejemplo, (lista 4.5 3.5 0.0) devuelve la lista (4.5 3.5 0.0). La declaracin(setq pt1 (list 4.5 3.5 0.0))assigns the list (4.5 3.5 0.0) to pt1, and also returns (4.5 3.5 0.0).The function car returns the first item of a list, so that if pt1 is the list of the x, y, and z coordinates of a point,(car pt1) would return the value of the x-coordinate of the point (4.5 in this case)The function cdr returns all of the items in a list except the first item, so that in our example of the list pt1,(cdr pt1) returns the list containing the y and z coordinates of the point pt1 (this would take the form (3.5 0.0)in our example because lists are contained within parentheses, as we discussed in lesson two of this series).Consider the following statements:asigna la lista (4,5 3,5 0,0) pt1, y tambin devuelve (4.5 3.5 0.0). El coche de funcin devuelve el primer

    elemento de una lista, por lo que si pt1 es la lista de las x, y y coordenadas z de un punto, (coche pt1)devolvera el valor de la coordenada x del punto (4.5 en este caso) de la funcin cdr devuelve todos loselementos de una lista excepto el primer elemento, por lo que en nuestro ejemplo de la lista pt1, (cdr pt1)devuelve la lista que contiene las coordenadas y y z de la pt1 de punto (Esto tomara la forma (3,5 0,0) ennuestro ejemplo ya listas figuran entre parntesis, como ya comentamos en leccin dos de esta serie).Considere las siguientes declaraciones:(setq pt2 (list 2.0 3.0 0.0))(setq pt2x (car pt2))(setq pt2yz (cdr pt2))(setq pt2y (car pt2yz))The value of pt2 is (2.0 3.0 0.0), the value of pt2x is simply 2.0 (the first item of the list of pt2), the value ofpt2yz is (3.0 0.0) because it is the list of all except the first element of pt2, and finally the value of pt2y is 3.0(the first element of the list of pt2yz).

    Es el valor de pt2 (2.0 3.0 0.0), el valor de pt2x es simplemente 2.0 (el primer elemento de la lista de pt2), elvalor de pt2yz es (3.0 0.0) porque es la lista de todos excepto el primer elemento de pt2, y finalmente el valorde pt2y es 3.0 (el primer elemento de la lista de pt2yz).We could combine the last two statements as:Podramos Combinamos las dos ltimas declaraciones como:(setq pt2y (car (cdr pt2)))according to the usual techniques for nesting functions in AutoLISP, and the result for pt2y will be 3.0 asbefore.segn las tcnicas habituales para anidar funciones en lenguajes y el resultado de pt2y ser 3.0 como antes.We may therefore always extract the second item of a list of any length simply by using the combinedfunctions (car (cdr list))Siempre, por tanto, podemos extraer el segundo elemento de una lista de cualquier longitud simplementeutilizando las funciones combinadas (coche (cdr lista))Can you see how to extract the third item of a list which contains any number of items using the car and cdrfunctions in some combination?The solution is (car (cdr (cdr list)))Puedes ver cmo extraer el tercer elemento de una lista que contiene cualquier nmero de elementosmediante las funciones car y cdr en alguna combinacin? La solucin es (coche (cdr (cdr lista)))AutoLISP provides functions which are combinations of car and cdr. These functions are formed by retainingthe initial 'c' and the final 'r', and combine the 'a' and 'd' according to the order in which the 'a' of car and the 'd'of cdr appear in the intended combinations of car and cdr. Thus cadr is equivalent to (car (cdr .....)) andcaddr returns the same result as (car (cdr (cdr ...))).

  • 7/31/2019 An Introduction to AutoLISP

    22/194

    Lenguajes proporciona funciones que son combinaciones de car y CDR These funciones estn formadas porretener la inicial 'c' y la 'r' final y combinan la 'a' y haba ' segun el orden en que la 'a' del coche y la haba ' decdr aparecen en las combinaciones previstas de coche y CDR Thus cadr es equivalente a (coche (cdr.....)) ycaddr devuelve el mismo resultado que (coche (cdr (cdr...))).Using this terminology, (car list) returns the first element of a list, (cadr list) returns the second item of thelist, and (caddr list) returns the third item of the list. Many other such combinations are possible, andAutoLISP allows nesting any combination up to four levels deep in a single function.Usando esta terminologa, (lista de coche) devuelve el primer elemento de una lista (lista de cadr) devuelve elsegundo elemento de la lista y (caddr lista) devuelve el tercer elemento de la lista. Muchos otros dichascombinaciones son posibles, y lenguajes permite anidar cualquier combinacin de hasta cuatro niveles deprofundidad en una sola funcin.A rectangle example, using LIST, CAR, and CADR functions.; RECTANG1.LSP program to draw a rectangle withUn ejemplo de rectngulo, usando funciones de lista, coche y CADR. ; RECTANG1.Programa LSP paradibujar un rectngulo conPage 14 of 64

    An Introduction to AutoLISP; lower left and upper rightpoints.

    ; inferiores izquierdos y superiores derecho puntos;(defun rectang1 ()(setq pt1 (getpoint "\nLower left point:")pt3 (getpoint "\nUpper right point:")p2x (car pt3)p2y (cadr pt1)pt2 (list p2x p2y)pt4 (list (car pt1) (cadr pt3))) ; end of point assignments(command "line" pt1 pt2 pt3 pt4 "c")) ; end of defun rectang1Here, we get the lower left and upper right points from the user. The points may be entered from the keyboard

    or by picking a position with the cursor and optionally snapping to a gridpoint or using an osnap mode. Wename the lower left and upper right points pt1 and pt3 respectively so that we retain the same ordering ofpoints as was used for the box example.Aqu, obtenemos la parte inferior izquierda y superiores derecha puntos por parte del usuario. Los puntospueden escribirse desde el teclado o recogiendo una posicin con el cursor y opcionalmente el ajuste a ungridpoint o utilizando un modo de osnap. Nombre de la parte inferior izquierda y superior derecha puntos pt1y pt3 respectivamente para que mantengamos el mismo orden de puntos como fue utilizado en el ejemplo decuadro.Notice now that we can separately define the x and y coordinates of the second point pt2 by defining p2x andp2y as shown. The car and cadr functions return the first and second items of a list, and it is convenient toregard these as the x and y components of points. This is a similar process to using the .x and .y filters ingeometry construction. We then define pt2 to be the list of p2x and p2y. We can of course extend thisapproach to the three dimensional case by including the z-coordinate (using caddr) in our list, but we assume

    here that all points are at the same z-level.Observe ahora que podemos definir por separado el x y y coordenadas del segundo punto pt2 por definicinp2x y p2y como se muestra. Las funciones de coche y cadr devolvern los artculos primeros y segundo deuna lista, y es conveniente considerar estos como x e y componentes de puntos. Se trata de un proceso similaral uso de los filtros .x y .y en construccin de geometra. A continuacin, definimos pt2 que la lista de p2x yp2y. Por supuesto podemos ampliar este enfoque a las tres dimensiones caso incluyendo la coordenada z(mediante caddr) en nuestra lista, pero suponemos aqu que todos los puntos estn al mismo nivel z.In our definition of point 4, pt4, we have by-passed the step of assigning variable names to the x and ycoordinates, and have made the car and cadr functions expressions of the list function. As you become morecomfortable with LISP programming you may decide to nest functions in this way, but don't get too

  • 7/31/2019 An Introduction to AutoLISP

    23/194

    complicated because you may need to modify and update your programs later on, and they should bereadable!En nuestra definicin del punto 4, pt4, tenemos discurra el paso de asignacin variable nombres de x e y lascoordenadas y han hecho el coche y cadr expresiones de funciones de la funcin de la lista. Como te vuelvesms cmodos con la programacin de LISP puede decidir anidar funciones de esta manera, pero nocomplicarse demasiado porque puede que necesite modificar y actualizar sus programas ms tarde y deberaleerse!The nth item of a list.The function (nth integer list) returns the nth element of list, where integer is the number of the element toreturn. AutoLISP numbers the elements of lists from zero upwards, so the first item of a list is obtained by(nth 0 list). If x = (3.2 4.5 0.0), (nth 2 x) returns 0.0 and (nth 0 x) returns 3.2.If pt11 = (2.0 2.5 0.0) and pt22 = (3.0 4.5 0.0), (setq pt33 (list (nth 0 pt11) (nth 1 pt22) 1.0)) would set pt33= (2.0 4.5 1.0).El ensimo elemento de una lista. La funcin (lista de enteros n) devuelve el ensimo elemento de lista,donde entero es el nmero del elemento para volver. Lenguajes los nmeros de los elementos de listas desdecero hacia arriba, por lo que se obtiene el primer elemento de una lista (n-sima lista 0). Si x = (3.2 4.5 0.0),(n x 2) devuelve 0,0 y (n-sima x 0) devuelve 3.2. Si pt11 = (2.0 2.5 0.0) y pt22 = (3.0 4.5 0.0), (setq pt33(lista (pt11 0 n) (n-1 pt22) 1.0)) establecera pt33 = (2.0 4.5 1.0).The cons and append functions.(cons item list) returns a list having item as the first element, and the elements of list as its remaining

    elements. In this sense, the cons function adds an item to the front of a list. For example, type the following atthe AutoCAD command prompt:Los contras y agregar funciones. (lista de elementos de contras) devuelve una lista con elementos como elprimer elemento y los elementos de lista como sus elementos restantes. En este sentido, la funcin de contrasagrega un elemento al frente de una lista. Por ejemplo, escriba lo siguiente en el smbolo de AutoCAD:(setq aa '(1 2 3 4 5 6))(setq bb (cons 99 aa))The first statement shows how a list can be created with the quote function, as we described in lesson 2 ofthis series. The list returned is (1 2 3 4 5 6).La primera instruccin muestra cmo se puede crear una lista con la funcin de la cotizacin, como descritoen la leccin 2 de esta serie. La lista devuelta es (1 2 3 4 5 6).The second statement returns the list (99 1 2 3 4 5 6)La segunda instruccin devuelve la lista (99 1 2 3 4 5 6)

    If list is an atom (has only one element), then cons returns a "dotted pair", which is a special structure inAutoLISP. Dotted pairs are the way in which AutoCAD associates items together in its data structure, where a'group code' number is associated with such items as object type, layer names etc., and is beyond the scope ofthis introductory course.Si la lista es un tomo (tiene slo un elemento), entonces contras devuelve un "par punteado", es unaestructura especial en lenguajes. Pares de puntos son la manera en que AutoCAD asocia elementos juntos ensu estructura de datos, donde un nmero de grupo de cdigo est asociado con elementos como tipo de objeto,etc. los nombres de capa y est fuera del alcance de este curso introductorio.When you use real numbers as the arguments for functions or in lists, you cannot omit leading zeros beforedecimal points, otherwise AutoLISP will assume that you intend a dotted pair, and this will result in the errormessage 'invalid dotted pair'.Cuando utilice nmeros reales como los argumentos de funciones o en las listas, no puede omitir ceros antespuntos decimales, lenguajes contrario asumir piensa un par de puntos, y esto dar como resultado el mensajede error 'no es vlido con puntos par'.Page 15 of 64

    An Introduction to AutoLISPThe append function adds an item to the end of a list, and is often used in programs to store many pointpositions in a single list so that the points can be used in the construction of polylines and general meshsurfaces. One example that we will see more of in later lessons is that of a cross-hatching program that is ableto perform cross hatching without the need to break lines that are not end-to-end. A useful and fairly commontechnique to cross hatch in this situation is to create a polyline by tracing over existing geometry, and then to

  • 7/31/2019 An Introduction to AutoLISP

    24/194

    cross hatch the polyline. Here is a part of the program in which a series of points is being added (appended) toa pointlist.La funcin de datos anexados agrega un elemento al final de una lista y se utiliza a menudo en programaspara almacenar muchas posiciones de punto en una nica lista para que los puntos pueden ser utilizados en laconstruccin de polilneas y superficies de malla general. Un ejemplo que veremos ms en leccionesposteriores es que de un programa de rayado que es capaz de realizar rayado sin necesidad de lneas de roturaque no son end-to-end. Una tcnica til y bastante comn cruzar hatch en esta situacin es crear una polilneapor rastreo sobre geometra existente y luego Cruz rompen la polilnea. Aqu es una parte del programa en elque se agrega una serie de puntos (aadido) a un pointlist.; Start collecting data and set layer to 'noplot'; Comenzar a recoger datos y establezca capa de 'noplot';(command "LAYER" "T" "noplot" "S" "noplot" "")(setq pdiff 1)(setq porig (getpoint "\n origin"))(setq ptlst nil);; Make a list of points for the 'pline'Hacer una lista de puntos para el 'pline';

    (while(> pdiff 0)(setq p (getpoint "\n next point"))(setq ptlst (append ptlst (list p)))(setq pdiff (distance p porig))); end of 'while' loop;; Draw a pline as a boundary for hatching; Dibujar una pline como lmite para incubar;(command "PLINE" porig "W" 0 0 (foreach p ptlst (command p)))In this fragment of our program, the layer 'noplot' is first thawed and set as the current layer, then an 'origin'

    point is defined. The user is requested to pick a series of 'next points' in order to create a closed polyline. Thevariable pdiff is used to check whether a selected point is coincident with the 'origin' point. If the distance'pdiff' is zero, the program comes out of a 'while' loop (more of that later!) and no more points are added tothe point list. Finally the poly line is drawn by supplying each point in turn to the pline command, usinganother type of repeating 'loop' known as the foreach function (again, more of that later).En este fragmento de nuestro programa, la capa de 'noplot' es primero descongelada y definir como la capaactual, a continuacin, se define un punto de "origen". El usuario es solicitado a recoger una serie de puntosprximos a fin de crear una polilnea cerrada. La variable pdiff se utiliza para comprobar si un puntoseleccionado es coincidente con el punto de "origen". Si la distancia 'pdiff' es cero, el programa sale de un'tiempo' bucle (ms de los que ms tarde!) y no ms puntos se agregan a la lista de puntos. Finalmente sedibuja la lnea de poli suministrando cada punto a su vez el comando pline, utilizando otro tipo de repetir'bucle' conocido como la funcin foreach (nuevo, ms de los que ms tarde).Be careful when adding points to a point list like this that you add the points as 'lists' with the list function, aswe have done in the cross hatch program example. To see the significance of this, try the following at thecommand prompt:First assign three points withTenga cuidado al agregar puntos a una lista de puntos como este que agregar los puntos como 'listas' con lafuncin de la lista, como lo hemos hecho en el ejemplo de programa de rayado. Para ver el significado deesto, intente lo siguiente en el smbolo del sistema: primero asignar tres puntos con(setq pt1 '(2.72 1.39 0.0) pt2 '(4.43 1.39 0.0) pt3 '(4.43 2.85 0.0))then collect those points into a point list with:luego reunir esos puntos en una lista de puntos con:(setq ptlst nil) (setq ptlst (append ptlst (list pt1)))

  • 7/31/2019 An Introduction to AutoLISP

    25/194

    this returns ((2.72 1.39 0.0)). Note the double parentheses! Note also that we could in fact initialize our ptlstwith the assignment (setq ptlst (list pt1)) instead of appending the first point to a null list.Esto devuelve ((2.72 1.39 0.0)). Tenga en cuenta los parntesis dobles! Tenga en cuenta tambin que enrealidad podramos inicializar nuestro ptlst con la asignacin (setq ptlst (lista pt1)) en lugar de anexar elprimer punto a una lista de nula.(setq ptlst (append ptlst (list pt2)))this returns ((2.72 1.39 0.0) (4.43 1.39 0.0)). Note that we now have a list of 2 items, each of which is itself alist of 3 items. Now try adding the third point without the 'list' function:Esto devuelve ((2.72 1.39 0.0) (4.43 1,39 0.0)). Tenga en cuenta que ahora tenemos una lista de 2 elementos,cada uno de los cuales es en s una lista de 3 elementos. Ahora intente agregar el tercer punto sin la funcin de'lista':(setq pt3 (append ptlst pt3))this returns ((2.72 1.39 0.0) (4.3 1.39 0.0) 4.43 2.85 0.0)In the last case, the coordinates of point 3 have not been made into a list, and the three coordinates appear asseparate items, which is not the intended format. If we now extract the third item of this list we will return thenumber 4.43 instead of the intended list of three numbers.En este ltimo caso, las coordenadas del punto 3 no se han hecho en una lista, y las tres coordenadas aparecencomo elementos independientes, que no es el formato deseado. Si ahora extraer el tercer elemento de esta listanos devolver el nmero 4.43 en lugar de la lista prevista de tres nmeros.Page 16 of 64

    An Introduction to AutoLISPThe other functions for dealing with lists are:Las otras fu