From: rurban@xarch.tu-graz.ac.at (Reini Urban) Newsgroups: comp.cad.autocad,alt.cad.autocad,alt.answers,comp.answers,news.answers Subject: comp.cad.autocad AutoLISP FAQ (part 1/2) - general Followup-To: comp.cad.autocad Date: 28 Jul 1997 16:00:02 GMT Organization: TU Graz-Fac.of Architecture & X-RAY Graz Message-ID: <5rifm2$sdh@fstgal00.tu-graz.ac.at> Reply-To: rurban@sbox.tu-graz.ac.at (Reini Urban) Summary: AutoLISP is a scripting language for AutoCAD, a wellknown CAD package. This AutoLISP FAQ is posted to comp.cad.autocad, alt.cad.autocad and *.answers bi-weekly. Keywords: FAQ, AutoLISP, AutoCAD Posted-By: auto-faq 3.2.1.4a Archive-name: CAD/autolisp-faq/part1 URL: http://xarch.tu-graz.ac.at/autocad/news/faq/autolisp.html Version: 1.9 Last-modified: 20.Jul 1997 Posting-Frequency: bi-weekly Copyright: see Appendix [A] Welcome to the comp.cad.autocad AutoLISP FAQ! by Reini Urban <rurban@sbox.tu-graz.ac.at> AutoLISP is a scripting language for AutoCAD, a wellknown CAD package. This AutoLISP FAQ is posted to comp.cad.autocad, alt.cad.autocad and the *.answers groups bi-weekly. The (incomplete) AutoCAD FAQ is at http://www.cadence-mag.com/library/FAQ and not posted to comp.cad.autocad yet. The contents and the samples apply to all releases of AutoLISP since Release 10, including the third-party versions ACOMP and Vital Lisp. There's no special AutoLISP newsgroup. Source code of all functions in this FAQ is in FAQ-CODE.LSP (location see [A.1]), there's also a winhelp file. Thanks to all who have contributed. Corrections and contributions always welcome. This is part 1/2 of the AutoLISP FAQ v1.9, which consists of: AutoLISP FAQ (part 1/2) - general AutoLISP FAQ (part 2/2) - samples, code | changes, + new in items from this version to the last posted version, intermediate personal comments and uncertainties in <..> ----------------- Table of Contents ----------------- part 1: - general [0] The Future of AutoLISP? Should I learn it or VB instead? [1] Where can I find AutoLISP routines on the Internet? [1.1] Are the comp.cad.autocad articles stored somewhere? [1.2] AutoDESK's SDK [2] What are the best books to learn AutoLISP? [2.1] Online AutoLISP documents, Winhelp [2.2] AutoLISP Coding Style [3] How do I debug AutoLISP programs?" | [3.1] Native AutoLISP debuggers [3.2] Modular style, TRACE [3.3] break function, debug print [4] How can I protect my AutoLISP programs? [4.1] Kelvinate [4.2] Protect [4.3] Kelvinate and Protect | [4.4] Convert 3.3 [4.5] acomp [4.6] Vital Lisp Pro [4.7] Lisp2C [5] AutoLISP compiler? [5.1] acomp [5.2] Vital Lisp Pro [6] AutoLISP editors and other tools? [6.1] AutoLISP editors [6.2] Parenthesis checkers [6.3] Pretty Printers [7] AutoLisp problems and bugs (esp. with R13) [8] Sorting with AutoLISP [9] Recursion [10] Iteration with mapcar,... [11] My Lisp doesn't load at startup anymore [12] How to Autoload my programs? [13] How can I pass a variable number of arguments to a lisp function? [14] How can I avoid stack overflows? [15] (command "ROTATE3D") does not work! Why? [16] Lisp programs operating over multiple drawings -- [A] Disclaimer, Notes from the author [A.1] FAQ Locations part 2: - samples, code [20] General helper functions + [20.1] List manipulation [20.2] string manipulation [20.3] symbol->string [20.4] AutoCAD entity access [21] Sample Lisp programs: [21.1] Globally change texts, polylines, layer utils, datestamp [21.2] Plot dialog from within Lisp [21.3] (entmod),(entmake) Layers, without (command "_LAYER"...) [21.4] How to select multiple files in Lisp? (as in FILES-Unlock) [21.5] Replace multiple blocks [21.6] (vports), VIEWPORT entity, pixel conversion [21.7] Select all visible objects: zoom coordinates [21.8] How to write XYZ data of selected objects to a file? [22] Block Attributes [22.1] How to access block attributes? [22.2] How to MODIFY block attributes? DATESTAMP.LSP [22.3] How to UPDATE block attributes? [22.4] How to ENTMAKE a Block Complex Entity in AutoLISP [23] Polylines | [23.1] How to access polyline VERTICES? | [23.2] How to JOIN multiple lines to polylines? [23.3] Change WIDTH of multiple polylines [23.4] Create a polyline or spline: with (ENTMAKE) or (COMMAND) | [23.5] How to calculate the LENGTH of polylines? [23.6] How to revert the polyline direction? [24] Circle/Arc Geometry: BULGE conversion, some trigonometry [25] DCL: listboxes with tabs or monotext font [26] EED Extended Entity Data: Get and Store [26.1] Select objects on their EED with (ssget "X") [26.2] Get EED from an object [27] How to break a command in Lisp? [28] How to decode ACIS internal geometry with Lisp -- [A] Disclaimer, Notes from the author [A.1] FAQ Locations [B] Acknowledgements [C] Recent Changes ---------------------------------------------------------------------- Subject: [0] The Future of AutoLISP? Should I learn it or VB instead? AutoLISP will be definitely supported in future releases. VB was introduced to simplify Office Automation: ACAD <-> Excel-Access Both languages have advantages and disadvantages. You should have a look at both. VB seems to be more graphical and AutoLISP more logical. The new VBA (end of 97) will be extremely fast. See also [5.2] ------------------------------ Subject: [1] Where can I find AutoLISP routines on the Internet? Some of the big AutoCAD shareware sites with Lisps are: CADalog - The AutoCAD Shareware Clearinghouse (Mike Clark) http://www.cadalog.com with search Rolling Stock Software (David Whynot) http://www.buildingweb.com/cadsyst/ PIRS Online (tm) http://Biz.rtd.com/insa/ They are specialized in AutoCAD related software and have a very good AutoLISP collection. Other professional AutoLISP shareware sites post their URL's to the newsgroup too. Some other sites with AutoLISP collections are: xarch AutoCAD Info & Tools (Reini Urban) http://xarch.tu-graz.ac.at/autocad/ (with search) CADENCE magazine code (Peter Sheerin) http://www.cadence-mag.com/code/ CADalyst magazine code (compiled by "Hot Tip Harry" Art Liddle) http://www.cadonline.com/ with search AutoCAD Tech Journal code (Peter Sheerin) http://www.atj.com/ The CADshack (Jeff Foster) http://www.cadshack.com/lispfile.htm SimTel - Coast To Coast - Archive (mostly old stuff) http://www.coast.net/SimTel/msdos/autocad.html http://www.coast.net/SimTel/win3/cad.html Bob Jones http://www.io.com/~bcjones/files.html Henry Francis http://www.ac.net/~coopfra/ Owen Wengerd http://www.manusoft.com/ Desi Moreno http://www.invsn.com/desmos/autolisp.htm Dr.Lisp Utilities (Alexander Medwedew) http://tribeca.ios.com:80/~compvent/drlutils.html UCCB AutoCAD and AutoLISP page (Paul Standing) http://ucad1.uccb.ns.ca/acad/cad.htm Theo L.A. Groenenberg http://www.dra.nl/~acadvice/autolisp.htm At http://www.autodesk.com/support/techdocs/techdocs.htm there are documents from the Autodesk Product Support answering technical questions. (Their FAQ's) [1.1] Are the comp.cad.autocad articles stored somewhere? There is no comp.cad.autocad archive or such a thing, but there are some search machines which store news articles. In particular: * http://www.dejanews.com/ - The biggest news archive directly with http://search.dejanews.com/dnquery.xp?query=~g%20comp.cad.autocad * http://www.altavista.com/ http://www.altavista.digital.com/cgi-bin/query?pg=aq&what=news * http://www.excite.com/ http://www.excite.com/search.gw?collection=news * http://www.phoaks.com/phoaks/comp/cad/autocad/ Index to Web resources Some specific news postings are also stored at http://xarch.tu-graz.ac.at/autocad/news/contents.html [1.2] AutoDESK's SDK Up to Release 12 a Software Development Kit was available directly at AutoDESK. The SDK1-2 was shipped with the international R12 for free. It included a lot of ADS and AutoLISP source code and libraries. With R13 AutoDESK provides a special developers network, comparable to Microsoft's, the ADN. The CD's are comparable to the old SDK but or more targeted to ADS and ARX developers. Contact your nearest AutoDESK headquarter for becoming a member. Some lisps are at http://xarch.tu-graz.ac.at/autocad/code/adesk/SDK2 <once again: What are the fees for the states, europe and the rest? and: Are SDK1 and SDK2 included with the quarterly CD-ROM's or may you order it for free as ADN member or Registered Developer?> ------------------------------ Subject: [2] What are the best books to learn AutoLISP? * "AutoLISP Reference Manual" by AutoDESK Press. Up to R12 it came as extra manual. With R13 it's only in Dynatext format on the CD-ROM. With R14 it is a winhelp. * "Maximizing AutoLISP" by Rusty Gesner, Tony and Mark Middlebrook, Tony Tanzillo. The new Maximizing AutoLISP R13 will be published hopefully this month. But the R12 book is still worth buying yet, though it's sold out. More at http://www.group-a.com/~rusty There are a lot of more AutoLISP books around. A very good Lisp (not AutoLISP) book is "Lisp" by Winston, Horn which is recommendable even for AutoLISP programmers. [2.1] Online AutoLISP documents, Winhelp R14 ships with the complete manuals converted to Winhelp. Available AutoLISP Winhelp files come with: * R14 (the whole bookset) * Visual Lisp (1.0 is free), see [1] * Vital Lisp, (help also included in the demo), see [6.1] For DOS there exists a memory resident program called LISPHLP.EXE (activates on Ctrl-RightShift-R, from 1988) LSPDOC.PL: At http://xarch.tu-graz.ac.at/autocad/lsp_tools/#lspdoc is a tool announced which automatically creates a winhelp for lisp files. [2.2] AutoLISP Coding Style Most of the samples being published by magazines or at various websites are very badly written, that's why AutoLISP is quite hard to learn for newbies too. Lisp is hard to read anyway because of it's briefness and countless parentheses. Therefore everybody is enforced to write clear, readable code. The AutoDesk samples are quite well written but sometimes they overdo it. :) There do exist automatic pretty printers or so called beautifiers (see [6.3]) which automatically formats your code according the standard. There's an excellent AutoDESK documentation about coding, commenting and intentation standards to keep lisp code readable. It's on the R12 CD-ROM in the SDK2 ACG.DOC or at http://xarch.tu-graz.ac.at/autocad/docs/acg.txt The most important points are: * Comment your code. Use ";;;" at row 1, ";;" inside the code (indented) and ";" for trailing comments (at row 39) * Follow the indenting standards as given by the pretty printers to be able to write better structured code, which is more readable. esp. for setq, defun, if, cond, progn * Try to avoid global variables. If you use them (for efficiency) clarify them with asterics around them and uppercase, i.e: *GLOBAL* * Don't forget to localize your variables (behind / in the defun parameter list). Only for debugging purposes you may temporarly undefine them. * Name protection: since autolisp provides no protected namespace and it's easy to overwrite even system functions, please use unique short prefixes, at least when you publish or give away your code. I use UR_ for functions and UR: for variables. The ADGE and adesk forces even 4 letter prefixes. Then your names are safe from being overwritten by other kamikaze functions. * Always use the leading underscore with any string (commands and options) given to command and osnap. There are even enough commercial programs which do not work on international versions. (command "_PEDIT" ss "_J") is better than (command "PEDIT" ss "J") * Don't do too much setq's: Lisp was originally a functional language, without any variables. There are enough constructs which work efficiently with lists without the need of storing values intermediatly in symbols. (see code samples [22]...) But for readability and debugging purposes you should always set symbols. * An old lisp rule is: Any good function is not longer than 6 lines. (And Lisp is the second oldest computer language, invented by John McCarthy at the MIT in the late 50's) * prefer cons over append: three conses and one reverse is better than one append. But there are some tricks with append (omitting nil) which allows its use (see esp. Serge's samples: remove at [11] or a style comparison at [23.1]) * use english symbols and comments * Don't use t,min,max or last as symbols! These are system functions! ------------------------------ Subject: [3] How do I debug AutoLISP programs? [3.1] There are three native AutoLISP debuggers: * acomp for R10 had one, free you can still use it with R12 DOS, but then you've got only the R10 lisp functions, i.e. no wcmatch function * Vital Lisp Professional has it in the IDE (the best). See [5] * ld, AutoLISP Debugger for R14, R13c4 and R12/DOS from cz (new and free) at http://www.cadstudio.cz/ftp.htm See the section on "[5] AutoLISP compiler?" [3.2] Modular style, TRACE The best support you can have for debugging is write your code in a well designed, modular style, pulling out distinct tasks into separate functions and then liberally using nested function calls. This will allow you to use the (TRACE) function as needed to locate any errors. [3.3] You may include break functions and debug print into your source code. Examples: ;;; Debugging functions (defun break (s) (if *BREAK* (progn (princ "BREAK>> (stop with <Enter>)\nBREAK>> ")(princ s) (while (/= (setq s (getstring "\nBREAK>> ")) "") (print (eval (read s))))))) ;bugfix from v1.3 (defun dbg-print (s) ;accepts atoms and lists (if *DEBUG* (if (listp s) (mapcar 'print s) (print s)))) (defun C:DEBUG () (setq *DEBUG* (not *DEBUG*))) ;switch it on and off (defun C:BREAK () (setq *BREAK* (not *BREAK*))) (defun CONT () (setq *BREAK* nil)) ;cont. without any interruption For a usage example see: http://xarch.tu-graz.ac.at/autocad/news/break_ex.lsp ------------------------------ Subject: [4] How can I protect my AutoLISP programs? [updated] "You really have to protect it? If you just want to share routines with your friends, why not give them the code? Working with others can be a great way to get new ideas and lead to a better application. Some of the best utilities are ones my friends have improved or I have improved some of my friends utilities." [4.1] Kelvinate with kelv.exe (on the R12 CD-ROM or at the AutoLISP sites "[1]"). Free. De-Kelvinate lisp's with any pretty printer, see [6.3]. But symbol names will stay garbled and comments are lost. [4.2] Protect with protect.exe (on the R12 CD-ROM or at the AutoLISP sites "[1]") Note that there exist unprotectors. Free. [4.3] Kelvinate and Protect First kelvinate it to make it unreadable, then protect it. Free. [4.4] Convert 3.3 Shareware Lisp En-/Decryptor by Maciej Lukasiewicz, Sweden. With Convert encrypted "Protected Lisps" cannot be decrypted by other programs only by Convert. [4.5] acomp AutoLISP compiler acomp.exe, on the R12 international release or at the AutoLISP sites. Free. more docs about acomp are at http://xarch.tu-graz.ac.at/autocad/bi4 See also "[5.1] AutoLISP compiler?" [4.6] Vital Lisp Pro http://www.basissoftware.com/vill.htm say "ViLL", quite expensive. See also "[5.2] AutoLISP compiler?" [4.7] Lisp2C Lisp to C converter, for R12,R13 Dos,Win (Watcom, Metaware, MSVC Libs). You need to own such a C compiler. Quite expensive. http://www.basic.si Summary: Serious encryption is only done with Vital Lisp. Kelvinating makes Lisp files unreadable and load faster. Protected [4.2] lisp files can be easily decrypted. The others are not decryptable. With Convert -e$GUARD encrypted Lisps can only be unprotected with Convert. ------------------------------ Subject: [5] AutoLISP compiler? There are two AutoLISP compilers: [5.1] acomp Acomp was supported up to R12 for the international releases only. It is free. Doesn't work with R13 nor with the domestic R12/Win. See http://xarch.tu-graz.ac.at/autocad/bi4 [5.2] Vital Lisp Professional [updated] by Basis Software Inc. USA. Simply the best. License-free runtime modules for R12/R13/R14 DOS/Windows/NT See http://www.basissoftware.com/vill.htm There's a free demo available. Current version is 3.0 The R14 version (ViLL 3.0) includes ActiveX (VB) and reactor support. See also [6.1] and [4.6] Summary: AutoLISP compilers as other Lisp compilers are bytecode compilers, which need a runtime system. You cannot create standalone programs, though with ViLL you create a stand-alone ARX. The symbols are encrypted. ------------------------------ Subject: [6] AutoLISP editors and other tools? [6.1] AutoLISP editors Vital Lisp There's a Lite Edition (just the editor) for $50, a Standard Edition for $350 (+ debugger) and the Professional Edition for $675 (+ compiler, extensions). With the Standard Edition you've got an excellent tool. See the section on "[5.2] AutoLISP compiler?" LispPad Nifty Windows Lisp Editor by Tony Tanzillo. http://ourworld.compuserve.com/homepages/tonyt/LispPad.htm A early version is included in the book Maximizing AutoCAD, http://www.group-a.com/~rusty The release version should be out in the first quarter of 1997 and will be announced at the newsgroup. Visual Lisp A very nice Windows Lisp Editor, Version 1.0 is even free. See "[1]" WCEDIT 2.02 ADS editor for DOS R12, can evaluate lisp code from within the editor, free. See "[1]" MultiEdit Pro 7.01g This is a expensive programming editor for Dos and Windows. It doesn't provide Lisp syntax checking or pretty printing, but everything else. See http://xarch.tu-graz.ac.at/autocad/adge/CAMP_Adge96_lisp.html for a complete description. Homepage at http://www.amcyber.com/ CODEKEY commercial, with internal pretty printer, protect, unprotect, kelvinator, <availability?> ALLY 3.0 and CADET Shareware Lisp Analyzer and Editor. See "[6.2]" pred free, small dos editor which provides parenthesis highlighting. At ftp://xarch.tu-graz.ac.at/pub/autocad/lsp_tools/pred.zip A similar editor is ADE. Emacs for NT Huge editor and quite hard to learn but it's written and customizable in lisp. Free, for all platforms. Check out http://xarch.tu-graz.ac.at/autocad/lsp_tools/ntemacs.html There are some others, which are either not that good (ADE) or I have no description yet. For more lisp IDE discussion see http://xarch.tu-graz.ac.at/autocad/adge/CAMP_Adge96_lisp.html [6.2] Parenthesis checkers lck21b.zip LCK Lisp Checker 2.1b (graphical) paran.zip simple PARNCH.ZIP simple ALLY30.ZIP Lisp analyzer. Checks syntax and prints statistics (function dependence tree). At [1] There are also some AutoLISP programs, which count parenthesis. [6.3] Pretty Printers external: FMT202S.ZIP Lisp, DCL and FRM source code formatter. Not checked yet. LB.EXE AutoDESK's source code beautifier in the SDK or at "[1]", got problems with longer strings, and new-style in-line comments. PPRINT.LSP in the SDK, see [1.2], or at "[1]" internal: Emacs, Vital Lisp and Codekey provide internal beautifiers as I'm aware of it. All of the tools and more are at http://xarch.tu-graz.ac.at/autocad/lsp_tools/ or at your nearest AutoLISP site "[1]" ------------------------------ Subject: [7] AutoLisp problems and bugs (esp. with R13) There are almost no known serious AutoLISP bugs. The language interpreter itself (ACADL.EXE/.EXP) works undoubtedly well. But there are some restrictions based on the CAD or Proteus (DCL) engine. And there are often faulty SUPPORT lisp programs. (i.e. DDMODIFY.LSP) * acad_strlsort: Strange sort order in Windows The chars in Windows are not sorted on its integer representation. Windows: (acad_strlsort '("-1" "+1")) -> ("-1" "+1"), DOS: (acad_strlsort '("-1" "+1")) -> ("+1" "-1") Both: (mapcar 'ascii ("-" "+")) -> (45 43) More at http://xarch.tu-graz.ac.at/autocad/docs/strlsort-bug.html * ai_propchk (ai_propchk) was converted to C:AI_PROP in the R13c3 update patch, to be able to be repeated from the command line with Enter. "The AutoLISP function ai_propchk has been changed to c:ai_prop so that it behaves similarly to other commands. This allows pressing return to bring back DDMODIFY if selected from the toolbar." see http://www.autodesk.com/support/techdocs/acadce/td111682.htm * faulty action callbacks in r13 dcl code crash AutoCAD There is a bug in R13 where AutoCAD crashes with a Fatal Error if an error occurs in AutoLisp code during an action callback from a scroll bar in a dialog box. For instance, if you try to evaluate a null function during the callback, AutoCAD crashes instantly. Technically, this isn't a bug in the AutoLisp interpreter, but we would still call it an AutoLisp bug. * You cannot rely on bitvalue 64 in flag 70 in symbol tables anymore in R13, but in all prev. releases. Inserted blocks may have 64 not set. Same in R14. What else? See the unofficial AutoCAD buglist compiled by Steve Johnson for more faulty AutoLISP programs and behaviours at http://www.awa.com/nct/software/13bug04.html, actually *01-05.hmtl (esp: 33, 124, 126, 127, 139, 153, 158, 165, 176, 182, 192, 193, 238, 240, 254, 272, 295) * Protected Lisp Files Then of course there's the bug in pre-c4a r13's which caused protected lisp files to not stay protected in memory. In our opinion, this problem needs to be made known to all, so that developers don't inadvertently assume their protected code is safe from prying eyes. <This faq topic caused a major problem in adesk's cis forum> * Limited number of open selection sets (bound to a symbol) They are intermediatly stored in temporary files. Get rid of not needed selection sets with setting the symbols to nil and run (gc), the garbage collector, which actually closes those files. The maximal number depends on the operating system, i.e. in DOS of the FILES= value in CONFIG.SYS * Numbers: range, accuracy Integer numbers are internal long fixnums (signed, 32-bit), but the communication from AutoLISP to AutoCAD accepts only 16-bit short fixnums, in the range -32766 .. +32767, because AutoCAD needs only short fixnums. Floating point numbers are doubles (32-bit IEEE). All internal AutoLISP and AutoCAD numerical calculations work with this double format, which should be sufficient. At least the first 14 decimal places are exact. However with a lot of geometric comparisons there often occur round off errors, so that it's wise to compare points with (equal pt1 pt2 1e-6) ; 0.000001 rounding error tolerance instead of (equal pt1 pt2), esp. with angles. see http://www.autodesk.com/support/techdocs/acadfc/td301207.htm * acomp's (eq) strictness With "[5.1] acomp" compiled code you have to take care that the (eq) behaviour in BI4's is much stricter than in plain AutoLISP. In AutoLISP (eq "1" "1") is T where in acomp compiled code it's nil. The following are no real bugs, that make AutoLISP crash or return false results. They are just bad language implementations. * (and) and (or) should return the value of the not-NIL argument instead of T. http://xarch.tu-graz.ac.at/autocad/docs/and-bug.html * (max) and (min) should handle string types too, because < and > accept strings. * see (acad_strlsort) above. * for stack overflow errors see [14] ------------------------------ Subject: [8] Sorting with AutoLISP I've set up a AutoLISP sort overview at http://xarch.tu-graz.ac.at/autocad/lisp/#sort In Lisp the mostly used sort method is merge sort (also used in (str-sort) in AutoDesk's TABLES.LSP sample) because that's a natural method for lists. Normally (in C eg.) you use heap sort (for any data) or qsort (for random data) and insertion sort for the small lists (< 7) or sublists within the algorithm. There is lisp code for shell-sort, bubble-sort, insertion-sort, quick-sort available for any data, lists of lists and indeces to lists. In lisp you can pass the predicate function to sort which is evaluated at run-time. (here called 'method'). That's why you need only one sort function for multiple data types (i.e. numbers, points on x or y, strings, ...) (sort data method) ;method: less-than-predicate ;default for numbers: '< Some sample timings from http://xarch.tu-graz.ac.at/autocad/lisp/sort/ur_sort.lsp sorting 100 elements: bubble sort : 13.639008 sec/ 30.08% insertion sort: 13.368042 sec/ 29.48% (fast for sorted lists) shell sort : 13.478973 sec/ 29.73% (poor implementation) merge sort : 2.232971 sec/ 4.92% quick sort : 2.433960 sec/ 5.37% vlx-sort : 0.099976 sec/ 0.22% (Vital Lisp internal) acad_strlsort : 0.089996 sec/ 0.20% (AutoLISP internal, strings) ------------------------------ Subject: [9] Recursion This is not a often asked question but a very interesting one, because Lisp itself is defined recursively and it's often the easiest way to articulate problems. There some fine documents about recursion at http://xarch.tu-graz.ac.at/autocad/lisp especially the http://xarch.tu-graz.ac.at/autocad/lisp/recursive.html tutorial by Dennis Shinn. It explains in great detail: (defun fact (n) (cond ((zerop n) 1) (T (* n (fact (1- n)))))) Note: There's also a self-modifying example of this function explained at http://xarch.tu-graz.ac.at/autocad/lisp/self-mod.lsp ------------------------------ Subject: [10] Iteration with mapcar,... Same as with recursion this is not a often asked question, but it's quite hard to understand too. Iterative statements in AutoLISP are: (while), (repeat), (foreach) and (mapcar). We use them widely in this FAQ code because they allow brief code. There's a short course in LAMBDA, QUOTE, MAPCAR... by Vladimir Nesterowsky: >> there are 14 paths and 12 pigs. >> How can there be 24 ducks? >> Is there a lisp command that will allow me to pick these >> lines of text, and recognize the number(s) in each line, >> in order to, say, raise each number by two? >> Leaving the sentence structure, etc, intact? This is one way. (I am sure there are many other ways) (defun mult2 (strng) ; (c) by Vladimir Nesterowsky (strlgather (mapcar '(lambda (s / n) (if (zerop (setq n (atof s))) s (rtos (* n 2)))) (strlparse strng " ")) ; parse by spaces " ")) ; gather back with spaces explained at http://xarch.tu-graz.ac.at/autocad/lisp/transpose.001.html ;;; flip rows and columns in a matrix (defun transpose(l) ; (c) by Doug Wilson (apply 'mapcar (cons 'list l))) is explained in detail at http://xarch.tu-graz.ac.at/autocad/lisp/transpose.002.html ------------------------------ Subject: [11] My Lisp doesn't load at startup anymore Lisp files that should be loaded at startup should be in ACAD.LSP. Some Lisps that are required for your menu to work should be in your menu.MNL file. The menu.MNL file should load ACAD.MNL (if its another) Lisp files that call commands should be defined in the S::STARTUP function in ACAD.LSP. This function is called at startup after the initialization automatically. Otherwise you'll get "Command list interruption (6 . 2)" errors. (load) lisp files without any absolute pathname or extension searches the program in the usual AutoCAD searchpath, which is 1) the current directury 2) the acad.exe directory 3) all other directories defined in the ACAD environment variable (under windows set in the Preferences box, SUPPORT paths) If your program doesn't load anymore though it should, maybe check your AutoCAD search path settings. An technical explanation of the loading process of acad, including all lisp files, which are loaded on different platforms, is given at http://xarch.tu-graz.ac.at/autocad/urban/urban-eng.html#Loading_Explicitly With acadlc (acomp) and the domestic release of AutoCAD R12 ACAD.LSP is not loaded automatically. Therefore you must append (load "ACAD" -1) to your ACAD.MNL. Sample ACAD.LSP: ;;;ACAD.LSP ;;; Fred the Beaver, 12/12/94 (load "init" -1) ; this loads some tools of mine (defun S::STARTUP () (load "new-end" -1) ; this redefines the END command ) The -1 provides (load) from interrupting the startup process on any error in a lisp. If an error at load-time occurs -1 is returned, but the evaluation does not stop. -1 can be any atom as well. Sample code to enhance S::STARTUP in your code (with Vital Lisp compiled code this will not work, it must be uncompiled) (defun MY::STARTUP () ;your startup code goes here .. (princ) ) (setq S::STARTUP (if (and S::STARTUP (listp S::STARTUP)) ;already defined in ; ACAD.LSP or elsewhere (append S::STARTUP (cdr MY::STARTUP)) ;append your code MY:STARTUP)) ;just your code or the simple way: (if (and S::STARTUP (listp S::STARTUP)) ;usually called consp (setq S::STARTUP (append S::STARTUP (list func '(princ)))) (setq S::STARTUP (list nil func '(princ)))) See also "[12] How to Autoload my programs?" ------------------------------ Subject: [12] How to Autoload my programs? [updated for R14] How to load my programs automatically? You can either load your whole program at startup (see "[11] My Lisp doesn't load at startup anymore") which needs more time and memory at startup time, or you can define them via the autoloading mechanism. With R14 ARX programs use a new autoloading scheme with some registry settings and not from ACADR14.LSP anymore. Look at the end of ACADR12.LSP resp. ACADR13.LSP how AutoCAD autoloads its programs. ;;;===== AutoLoad LISP Applications ===== ... (autoload "dline" '("dline" "dl")) ... This defines the commands DLINE and DL in the list to be loaded from the file DLINE.LSP when the user first calls the command DLINE or DL. Before that the function is simply defined like this one: (defun C:DL () (load "DLINE")(C:DL)) In fact the definition is more complicated because of error handling. After the first call the function is overwritten with the definition in the program. Advantages of autoloading: * Startup is faster, because you dont have to load all your lisp files. You just define the simple *wrapper* definition as above. This is done by the (autoload) function. * You need less memory. Disadvantages: * On errors in your program you will fall into a never ending loop, which will only stop after a stack overflow or Ctrl-C Note: with acomp compiled code even Ctrl-C is impossible. Insert then a call to an uncompiled (princ) somewhere. * You have to define and maintain all command names from your program in the autoloader definition. Changes to the lisp filename or the command name will cause the above error. Where to put your (autoload) definitions? * Not to ACADR13.LSP. * Well we recommend putting it to an initialization file of yours and not to ACAD.LSP because this is often changed by different applications and ACAD.LSP should be kept rather small. I.e. put it to a AUTOLOAD.LSP or INIT.LSP, which is loaded from ACAD.LSP. See "[11] My Lisp doesn't load at startup anymore" * It should be mentioned that users should *not* modify ACADR13.LSP (or ACADR12.LSP, although it wasn't "official" until r13). Since ACAD.LSP is not overwritten during upgrades, it is guaranteed to remain safe. In addition (as we saw with the R13c4a patch) if the ACADR13.LSP file has been modified, then the patch process may refuse to update it, thus resulting in program malfunctions. ------------------------------ Subject: [13] How can I pass a variable number of arguments to a lisp function? With AutoLISP this is not possible. You can either pass all your arguments in a list like this: ;;; print a variable number of arguments (of any type) (defun my-princ (x) ;; simple version, for better stuff look at the SDK2: PRINTF.LLB (if (listp x) (mapcar 'princ x) (princ x))) Or you have to define the function in ADS and export it to AutoLISP. Then you are free to write: (ads-print "Hello " "World " 1 2 3) or even (ads-printf "Hello %s %i %i" "World" 2 3) Look at Reini Urban's and Vladimir Nesterovsky's ADS samples at http://xarch.tu-graz.ac.at/autocad/ads for implementations of the above examples. Official wishes were pointed to AutoDesk regarding &optional as AutoLISP language enhancement, but it was not implemented in R14. ------------------------------ Subject: [14] How can I avoid stack overflows? In AutoLISP the stack size is hardcoded. It cannot be extended, but its size should be sufficient for most purposes. Most stack overflow errors occur on a program error of yours, preventing the system from falling into an endless loop, or from using recursive functions on large lists. Therefore you are limited to lists ~200 elements with recursive functions. You cannot decrease your used stack size with using less local parameters in your recursive function! However do not use APPLY, EVAL or MAPCAR to call your function recursively, because they eat up the stack. Using tail recursion doesn't help either. You'll have to convert your recursive function to a iterative one. (There is a mathematical theorem that says, that every recursive function can be converted to a iterative one, tail-recursive ones even automatically.) Iterative versions may use stack-like functions like (push) and (pop), but those versions store the stack on the heap (autolisp node space), which size is only limited by your amount of virtual memory available. You can test the stack overflow with this simple function: ;;; create a list of n numbers (zero based) (defun intlst (l n) (cond ((zerop n) l) (T (intlst (cons (1- n) l) (1- n))))) and try: (setq n 100)(while (intlst nil (setq n (+ 10 n)))(print n)) In AutoLISP of R12/DOS you reach the stack limit with (intlst nil 138), in A13/Win with (intlst nil 240), in acomp bi4's with (intlst nil 1240), in Vital Lisp IDE with (intlst nil 984). With Vital Lisp RTS the stack size is unlimited. With R10c10, the first dos extended lisp version, you could enhance the lisp stack size with the environment variable LISPSTACK. acomp for R10 had COMPSTACK. This is not possible anymore. Conversion to an iterative version yields the required results: (defun intlst (n / l) (repeat n (setq l (cons (setq n (1- n)) l)))) ;this looks ugly but it works The only possibility to physically enhance the stack size is to use the acomp interpreter ACADLC or Vital Lisp. See [5]. BTW: Better Lisp systems may automatically convert tail-recursive functions to iterative ones. ------------------------------ Subject: [15] (command "ROTATE3D") does not work! Why? Some commands are no internal AutoCAD commands, they are simple AutoLISP programs beginning with C: even if they are defined in ADS programs. Only native Rx applications export true commands. A list of all these commands are found in ACADR13.LSP in the AUTOLOAD section. (see also "[12]") All these commands have to be called with (C:ROTATE3D) instead of (command "ROTATE3D"). However ADS functions may take optional arguments. See the customization manual for more. i.e. (c:rotate3d ss p1 p2 angle) is also valid, even (rotate3d ...) ------------------------------ Subject: [16] Lisp programs operating over multiple drawings [title changed] "I am having trouble getting a lisp file that will open a drawing and continue running. Once the new drawing is opened the Lisp file ceases to exist in the Autocads memory. It has to be reloaded to recognise the commands." LISP memory is reloaded on a per drawing basis. There are some ways to execute a LISP on multiple drawings: 1) via a script that executes on multiple files. MYSCRIPT.SCR: (load "mylisp") _QSAVE _OPEN !nextdwg (load "mylisp") _QSAVE _OPEN !nextdwg ... 2) External 3rd party software such as RunLisp or DDSCRIPT automate step 1. 3) R14 has a new feature, called 'Persistent LISP'. Set it in Preferences-Compatibility-Persistent Lisp 4) Vital Lisp has a built-in variable to act as Persistent Lisp: (setq *VILL-NEW-FULL-INIT* nil) ;keep symbols between sessions ------------------------------ Subject: [A] Disclaimer, Notes from the authors If you think of questions that are appropriate for this FAQ, or would like to improve an answer, please send email to Reini Urban <rurban@sbox.tu-graz.ac.at> but don't expect an reply. This AutoLISP FAQ is (c) 1996,97 by Reini Urban. All rights reserved. This FAQ may be freely redistributed in its entirety without modification provided that this copyright notice is not removed. It may not be sold for profit or incorporated in commercial documents (e.g. published for sale on CD-ROM, floppy disks, books, magazines, or other print form) without the prior written permission of the copyright holder. Permission is expressly granted for this document to be made available for file transfer from installations offering unrestricted anonymous file transfer on the Internet and esp. to be included into the official AutoCAD FAQ. The sample code is, if not otherwise stated, (c) 1996,97 by Reini Urban and may be freely used, but not sold. The basic functions in [20] are, if not otherwise stated, (c) 1991-97 by Reini Urban and may/should be freely used. If this FAQ is reproduced in offline media (e.g., CD-ROM, print form, etc.), a complimentary copy should be sent to Reini Urban, X-RAY, Rechbauerstr. 38, 8010 Graz, Austria This article, the contents and the sample code, is provided AS IS without any expressed or implied warranty. It is intended to be included into the official AutoCAD FAQ. which for now is maintained by Peter Sheerin at http://www.cadence-mag.com/library/FAQ or if a new AutoCAD FAQ will make it (see the actual discussion), as a part of it. There will be some changes in the near future. Temporarly the new acad faq submissions can be watched at http://xarch.tu-graz.ac.at/autocad/news/faq/new-acad/ This AutoLISP FAQ will be posted bi-weekly (every 2nd saturday) to comp.cad.autocad, alt.cad.autocad and *.answers. Hope this and the AutoCAD FAQ will grow. [A.1] FAQ Locations Homepage of the HTML'ified version: http://xarch.tu-graz.ac.at/autocad/news/faq/autolisp.html The posted ascii versions (and always latest versions) are at http://xarch.tu-graz.ac.at/autocad/news/faq/autolisp.1 and http://xarch.tu-graz.ac.at/autocad/news/faq/autolisp.2 The Winhelp version (zipped with faq and code) is at ftp://xarch.tu-graz.ac.at/pub/autocad/news/faq/autolisp.zip The FAQ usenet archive is at ftp://rtfm.mit.edu/pub/usenet-by-hierarchy/comp/cad/autocad/ comp.cad.autocad_AutoLISP_FAQ or at http://www.faqs.org/faqs/CAD/autolisp-faq/part1/ The Lisp code from this FAQ is at ftp://xarch.tu-graz.ac.at/pub/autocad/news/faq/FAQ-CODE.LSP See also the cca glossary for common abbrevations at http://xarch.tu-graz.ac.at/autocad/news/faq/glossary.html Submissions for the new AutoCAD FAQ are stored at http://xarch.tu-graz.ac.at/autocad/news/faq/new-acad -- Reini Urban, 22.Jul 97
[
By Archive-name
| By Author
| By Category
| By Newsgroup
]
[
Home |
Latest Updates |
Archive Stats |
Search |
Usenet References |
Help
]
Send corrections/additions to the FAQ Maintainer:
Last Update August 13 1997 @ 02:03 AM faq-admin@faqs.org