Vous êtes sur la page 1sur 50

Free Website | free host | Free Web Page | BlueHost Review

Rafael Negron AutoLISP Notes 01.26.04 (Most of this information is summarized from AutoLISP Programming Course by Ron Leigh http://pw1.netcom.com/~rogh/autolisp/)

AutoLISP SYNTAX

COMMENTS - are not processed by the AutoLISP interpreter ";" is used for a one comment line - ;| is use to close in commenst that last for more than one line and is ended by |;

EXPRESSIONS AutoLISP programs are made up of expressions which accomplish a certain task. They are written in this format...

( function first-argument second-argument etc.... ) (/ w 2) the function is division, the arguments are w and 2, divide q by 2.

Syntax. The expression is list, meaning that it opens and closes with a parenthesis. The elements in the list are separated by spaces, the first element in the list is the function and the other list elements are arguments for the function. The function can be called the operator and the arguments as the operands.

THE AUTOLISP INTERPRETER There are three ways for AutoCAD to receive expressions/code. - You can type them in the command line, whenever you open and close something that you type with parenthesis, AutoCAD will use it AutoLISP interpreter and return you a value for your expression. - You can write them in a txt.lsp file and load it by typing appload and choosing your lsp file. - Using menus that contain expression attached to them.

* Remember to open and close with parenthesis (AutoLISP will return 1> , when your parenthesis are missing ) put spaces between list elements, and enter decimals with a leading zero ( 0.25).

Basic Arithmetic Functions - Normally in computers you enter the operators in between the operands such as (5*8) , but in AutoLISP you enter the operator first and then the operands later (* 5 8 ).

Addition + Subtraction Multiplication * Division / Square root sqrt

- You can put expressions within expressions, this is called nesting. When evaluating nested expression do it from inner to outer.

- Making a program that finds the area if a triangle. The area of a triangle can be found by finding half the sum of all sides, which will be S. And then finding the square root of the product of S, S-a,S-b,S-c.

S = (a + b + c) / 2 Area = (S (S - a) (S - b) (S - c))

;| Start Program Area Calculation Program Variables - a sideA, - b side"B", - c side"C", - area area of triangle, - p perimeter, - s intermediate value. |;

(defun c:area3 (/ a area b c p s) (setq a (getreal "/nWhat is the length of side A:")) (setq b (getreal "/nWhat is the length of sideA:")) (setq c (getreal "/nWhat is the length of side C:")) (setq p (+ a b c)) (setq s (/ p 2))

(setq area (sqrt (* s (-s a) (- s b) (- s c)))) (princ "/nThe area is " ) (princ area) (princ "/nThe perimeter is..") (princ p) (princ) )

;End Program

VARIABLES - is a symbol that points to a bit of information stored in memory - a variable can change the information it holds depending on what you declare it to be - they are set by using the setq function - after a value is assigned to a variable it can be retrived or referenced. - easiest way to display a variable is dump it by typing ! and the variable name, acad will disply it. - they are not case sensitive, but you should write them in lowercase - dont give variables names that are already pre-assigned or used by built in functions, these are called "reserved words" - to find out wether a variable is a reserved word, dump it - they should be short clear and concise, make it too long and it is harder to debug and is easier to make typos.

Setting Variables - setq variable_name value - you can set more than one variable in the same line by repeating variable_name value after each other.

The life of a variable - if you stay in the same drawing a variable will keep its value until assigned another one - local variables will lose its value when the program quits - lispinit , when set to 1 AutoLISP is initialized for each drawing clearing variables - when set to 0, AutoLISP will not initialize for every new drawing, keeping the variables.

Dcumentation - You should document your program so it is easier to rebug and maintain over the years. - It should include the name & purpose of the program, what the variables are and what they mean, and any other information that is not obvious. - Place comments after the ";" any thing after that in the line will be ignored. - Or if you want do several lines of comments you start it with ;| and close it up with |; - Put the list of variables in aa logical or alpgabetical order.

The defun function

(defun name (variables) )

- the defun functions works like the setq but it references multiple lines of code, so they can be called back to execute the program. It can define a function which is used within the code or a command which is referenced from the command line. - syntax consists of the name, the variable list, and the expressions.

First Argument - Name

- if you want it to be a command that can be called in AutoCAD put a "c:" in front of it

- functions can also be dumped by putting a ! in front of them.

Defining a function - the name is the first argument Defining a command - try not to give it a name that is aleady used by AutoCAD for a command.

Defining a "function" to be "called" from within a program. Name is like a variable, for example, circarea Called by placing name first in a list and sending any needed values, for example, (circarea 0.875)

Defining a "command" to be "run" at the command prompt. Name starts with c: for example, c:circarea Called by entering name at command prompt, then supply input when prompted. Can also be called like a function, for example (c:circarea)

Second Argument - The Varibale List - in a function the second argument is a list containing the variables that will receive values when it is called - the order in which the variables are listed are very important, the order in which they are listed should be the same order in which they are declared. - in a command no arguments are set to it, so it will be an empy list ()

Global and Local Variables

- global means that the variable retains it's value after the program quits - good for keeping settinsg stored - local means that the value is lost ( becomes nil) after the program quits. or if it had a previous variable before it then it turns back to that. - to make a variable in a function local put a forwward slash before the variables in the variable list - (defun booyah (len sp cp / ant green blue) ) - in this case ant, green and blue are local and len sp cp are global

Third Argument - Program expressions - After the name and the variable list you place all the program expressions. This can be as simple as one or three expressions as illustrated above, or it may be many pages of expressions. ; Practicing Functions (defun areab (base height) ;defines the function as areab with the expected variables as base height (* base height 0.5) ; the expressions that will be carried out when the function is called with the variblaes assigned to it. )

; Practicing Functions, the Pythagoerean Theorem (defun pythag (a b) ; defining the pythag function with a and b as its two arguments (sqrt (+ (* a a ) (* b b) )) ;the pythagorean theorem in LISP syntax

) ;closes the defun function

The get-functions - pause the prgram to receive user input - they all start with the letters get - to add a prompt to the get function add a string as an argument, - adding a \n arhe begining of a string will force the prompt to be displayed in the begining of a line. The "\" is a code and "n" stands for "new line". - leave a space after the end of your prompt message

getint - will wait until the user enters an integer. If you press enter then it will return a nil value, if you type in something like 2.25 (not an integer), it will tell you so and wait till you do enter one. getreal - will wait to enter a real number (2.25) or an integer Getdist function - Allows the user to input a distance either through keyboard or through the selection of two points (getdist "prompt")

getpoint - will wait for user to specify a point, - the user can select it with a mouse or enter the cordinates, -the program can enable a certain osnap mode to help the user out in selecting the point. -It returns a list of three real numbers which represent respectiveley x,y,z cordinates of the point.

-When you add a point argument to the function a trailing line is anchored to that point while the suer selects a point. It can be added before or after the prompt. (setq p2 (getpoint p1 "\nLocation of second point: ")) getcorner - is similiar to getpoint but that it requires a point argument, and will create a trailing box instead of a line when user is selecting a point getsring - waits for user to enter a string, up to 132 characters with no spaces (which will act just like the enter key), unless you add 1 as an argument which will accept a space as as the string. Enabling/Disabling Osnap modes (setvar "osmode" 1) 0- disable all osnap modes 1 - sets it to midpoint 2 - sets it to midpoint

- With a little code you can setup to getvar so you can remember the osnap mode before and then set it to what you want, and at the end of the program you can set osnap mode to what it was before.

(setq osnp (getvar "osmode") (setvar "osmode" 1) (getpoint "\nSelect center-point: ") (setvar "osmode" osnp)

Sets running Object Snap modes using the following bitcodes: 0 NONe 1 ENDpoint 2 MIDpoint

4 CENter 8 NODe 16 QUAdrant 32 INTersection 64 INSertion 128 PERpendicular 256 TANgent 512 NEArest 1024 QUIck 2048 APParent Intersection 4096 8192 EXTension PARallel

To specify more than one object snap, enter the sum of their values. For example, entering 3 specifies the Endpoint (bitcode 1) and Midpoint (bitcode 2) object snaps. Entering 16383 specifies all object snaps.

The initget function (initget value) - limits the value that the program will accept when that next get function is used. The value determines what limitation is put. - very useful so as to not let the user crash the program by entering wrong input type

1, null input not allowed 2, 0 input not allowed 3, null and 0 input not allowed

4, negative values not allowed 5, null and negative inputs not allowed 6, 0 and negative input values not allowed. 7, null, 0 and negative input values not allowed 8, cancels limit check. System Variables - AutoCAD uses these to store information about drawing and the environtment - Some of these are saved to the drawing, and some are saved in the registry which means they are consistent no matter what drawing you are using. - You can retreive and set system variables with getvar and setvar, respectively. - the type of value you will receive depends on the system variable itself, some are either 1 or 0 and some are lists. - the system variable is the first argument an is stored in a string, if you are setting a system variable the second argument will be what you want the system variable to be. - if you set a variable with a data type which is not compatible (either is not the right data type or range) it will reject it. For example you cannot set filletrad (fillet radious) to a negative number. examples... (getvar "osmode") (setvar "osmode" 3)

*list function- groups more than one value together, very useful for specifying point values. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Arithmetic functions that have numbers as arguments produce different outputs depending on the data types that are fed to it. If all the arguments are integers the value returned is an integer. If you provide a real as argument the output will be a real number.

So if you type in (/ 1 2) or any division which would give you 0, because its trying to give you a integer which has no decimal place. But if you type (/ 1 2.0) you will get 0.5 I would suggest to use real numbers whenever you can except where you specifically need an integer for function, for example repeat needs an integer to determine the amount of repetitions for the function. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Logic and Category Checks

T = represents true nil = represents false

(not expression) (or expression(s) ) (and expression(s) ) (xor expression(s) )

returns T for null items, nil for T itemrs returns T when any when at least one of the expression are T returns T when all of the expressions are T

(null expresion) returns T when expresion is null (atom expresion) (list p expression) (type item) returns T when the expression is an atom (as opposed to a list) returns T when the expression is a list returns the data type of the item

Trigonometric Functions

AutoLISP only has three tirgonometric functions - sin cos atan. - tan can be used by creating a function of it

atan function (atan angle angle)

*dont divide the ratio out of the atan command, AutoLISP determines the quadrant and size of the angle by analyzing the signs of the angle arguments

Defining tan in AutoLISP (defun tan (ang) (/ (sin ang) (cos ang))) Defining asin in AutoLISP (defun asin (sine) (atan sine (sqrt (- 1 (* sine sine))))) Defining acos in AutoLISP (defun acos (cosine) (atan (sqrt (- 1 (* cosine cosine))) cosine))

Geometric Functions - used for extracting and calulate information about know locations to calculate more calculations

Distance & Angle functions - distance p1 p2 - will return the distance of the 2 point arguments - returns a real number, when the two points are on different Z cordinates, it returns the 3d distance. - angle p1 p2 - returns the angle of the 2 point arguments - returns a real number in radian measure of the angle between point 1 and 2. - the angle is measure from the "3o'clock" line.

- the points can be at different z cordinates but it will be projected in x, y and give you that angle

Inters Function - (inters pt1 pt2 pt3 pt4 nil) - will return the point of intersection between two lines - pt1 pt2 is one line, pt3 pt4 is the other line - IF you specify nil as a 5th argument inters will consider the lines given as infinite in length.

Polar Function - polar basepoint angle distance - calculates a new point depending a basepoint, the angle in radians from the base-point and the distance from that basepoint - if the distance is negative the point will go in the opposite angle mentioned in the function - remember there is a difference between the angle between p1 and p2, and the angle between p2 and p1. - Example program using the polar function (setq a (list 0 0 0)) (setq b (polar a 0 5)) (setq c (polar b pi 5)) (command ".pline" a b c "c")

* You can use a combination of the previous functions to find points that are not lineraly related together, as in on the other hand you would have to use trigonometry, which can get very comples later on.

The Command function

command ".commandname" input "string_input"

- allows you to submit commands to the AutoCAD interpreter from lisp - input must be in the same order just as if you were typing it in AutoCAD. - first argument - represents the command name in string form

Example - drawing a circle with a diameter of 5 (setq a (list 2 5 ) ) (command ".circle" a "d" 5) - extra arguments - variables, expressions, strings for letter input, empty string "" to represent the enter key.

(command ".line" (list 0 0 0) (list 0 2 0) "")

- if you want the user to enter the input themselves you can type pause as an argument, this will stop the command and wait for the user to input.

- you can setup osnap filters before a pause to help the user out in selecting a point. - you can also repeat the same command without typing the function again just by typing the command argument again. for example...

(command ".circle" (list 0 0 0) 5 ".circle" (list 0 0 0) 10 ".circle" (list 0 0 0) 15)

- Figuring out the prompt sequence for commands that activate a dialog box. Just type a dash "-" in front of the command to bypass the dialog box. Ex. -array.

Repeat function

(repeat int [expressions]) Evaluates each expression a sepcfifed number of times ( must be an integer)

Arithmetic Logic Operators and Checks

Arithmetic Checks

= /= > >= < <= eq equal

tests for numerical equality, can have more than two arguments test for numerical inequality, can have only two arguments tests if first argument is greater than the second argument tests if first argument is greater than or equal to the second argument tests if first argument is less than the second argument tests if first argument is less than or equal to the second argument tests if the two values as setq by each other, ex. (setq w h) are eq. tests whether two expressions evaluate to the same thing

minusp zerop

tests wether an item is a negative number tests wether a number is equal to 0

Logic Checks

not null or and atom listp

negates the current T or nil value of the item. tests for a null item or list tests for at least one T expression among two or more test for all expressions to be T tests for an atom test for a list

boundp tests to see if a value is bound to an atom

type (type '15) (type 15) (type (setq b, 15.0)) (type "hello) (type (3.45 6.5 9.0) )

returns an item's data type SYM INT REAL or "floating point" STR LIST

*Additional types are (file descriptor), SUBR (subroutine),

PAGETB (function paging table), PICKSET (selection set), and ENAME (entity name). The last two types are manipulated only by the ss... and ent... functions.

Regarding Accuracy and arithmetic operators- sometimes there will be numbers that are very similiar until they get to the very far decimal places. This is because different data types will yield different levels of accuracy. Integers for example are completely accurate to their allowed range and floating point real numbers are accurate to 14-17 digits. Trigonometric functions will yield less accurate values. So when you enter a value yielded by a trigonometric function and a real number into a "=" you might get a nil, even though those two values theoretically should be equal. Therefore the equal function has a third argument that allows there to be a margin of error

Conditional Functions

"If" funtion - decides what to do if a condition is true or false

(if testexpr thenexpr elsexpr)

testexpression - expression to be tested thenexpression - what happens when test is not nil elseexpression - expression to be executed if test is nil.

* Some times you dont need operator type tests such as (= 5 3), but it can be a vlue, the if function wille evaluate to see if it is nil, if it is nil then its false.

* You can nest "if" functions within "if" functions but only do that if you have too. If a decision has more than 2 possible solutions you should use the cond.

(setq a (getreal "\nWhat is no.a")) (setq b (getreal "\nWhat is no.b")) (if (> a b) ; the test

(Princ "\nA is greater than b ") ; the then expression (if (< a b) (princ "\nA is less than B") (princ "\nA is equal to B") ) ) ; nesting another if to see if i is less than ; if so then print this ; if not then it must be equal ; close up the second if function ; close up the first if function

The "conditional" function

Each argument in the conditional function is a list, the first item in the list is the test, if it is T there othe expressions in the list is processed, if it is nil the next item in the lisrt is ignored and repeats the next argument (list) in the conditional function.

Each argumment in the conditional function is list, the first itmer in the list is the test, if it is T then the other item is evaluated and the cond function is terminated. If it is nil the next item in the argument list ignored and cond function will test the next argument list.

(COND

( (TEST) (EXPRESSIONS...)) ( (TEST) (EXPRESSIONS...)) ( (TEST) (EXPRESSIONS...)) ..... )

(setq a (getreal "\nWhat is no.a")) (setq b (getreal "\nWhat is no.b")) (cond ( (< a b) (princ "\nA is smaller than B")) ( (> a b) (princ "\nA is Greater than B")) ( (= a b) (princ "\nA is equal to B")) ) ;first test and expression ;second...

* It is very common to use the cond function when you have a test with many possible outcomes. GetKWord Function

The getkword is a function that is used get a key word our of several options at a prompt. A good example of the use of this function is the pline and the pedit command which has several options you can go through.

- the get kwordfunction must be initialized by the initget function which limits the what it will accept as the user input.

Example

(initget 1 "LE RI UP") (setq direc (getkword "\nSpecify RIght/LEft/UP:")) (princ direc)

This will ask the user for a direction and the initget function will accept le or ri as an allowed user input, the variable will then be one of those two. If the user enters somethng that is not in the initget function, then a message will tell the user "invalid option key word" and lets the user try again.

Adding a "1" as a first argument to the initget function when using the keyword will keep the user from entering a null response. Other numbers can be used to limit the response as covered in the initget function section.

The getkword function can be initialized to get integers but the variable will always be assigned a string.

ITERATION FUNCTIONS

The repeat function

- is the simplist loop function, it repeats a group of expression a number of times - no. of repetitions must be an integer - used when you know the amount of iterations needed

(repeat #_of_repetitions expressions)

(repeat 10 (setq num (1+ num)) (princ num) (princ " ") )

The While function - will repeat a group of expressions until a condition is met - the first argument is a test expression - used when you dont know the amount of iterations needed

(while test expressions)

(setq a 5) (setq counter 0) (while (> 100 a) (setq a (+ a 10))

; set a to 5 ; set the counter to zero, will show how many iterations were performed ; the test as long as this is true the expression will be evaluated ; increments a by 10 for every loop performed

(setq counter (+ counter 1)) ;increments the counter by 1 (princ a) program is done ;displays each variable for every loop to see how they change when

(princ "\n ") (princ counter) (princ "\n ") )

The foreach function

- the amount of repetitions is dependent on the amount of atoms in a list - assigns each value in the list to a variable

(foreach name list expressions)

name argument- assign each consecutive atom to this variable lisdt argument- which is what will determine the amount of iterations expression arguments- what will be done to the name value every repretition

(setq nlist (list 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)) (foreach v nlist (princ v) (princ "-"))

returns 1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-

LIST HANDLING

List Storage - when information is stored in memory, AutoLISP recrods it's location so it can be retrieved later. The setq function assigns a data value to a memory location and associates that memory address to the variable name. Diferent data types take up different amounts of space, reals take up as twice more space than integers and therefore are more accurate. For integers and reals there is a fixed amount of memoery set aside for them, but for data types such as lists ( which contain numerous values) it is not possible to address them with one variable because their lengths are unpredicable. So the elements in a list are in different memory registers but are linked together by their decrement registers. The variable holds an adress register (AR) which points to a value, and a decrement register (DR) which holds a pointer that points to the next variable AR. So when you assign a list to a variable, the variable only points to the first element in the list, which is linked with the next element by its decrement register.

List building and handling

list function - used in order to form a list - (list value_1 value_2 value_3.....)

cons function - used to add an item to the begining of a list, it returns a new list, so if you want to change the list you have to setq the list first. - ( cons 'value_to_add list_name ) - add an appostrophe to the value you want to add

append function - used to add another list at the begining of a previous list - ( append list_to_add list_name )

Null lists - null list are created usually for loops, which then add values to the list for each iteration. - (setq list () ) - or (setq list nil)

* Top level lists and sub lists, you can nest lists within lists such as (list ( 0 9 8 7 ( list 1 2 ) 5 4) returns ( 0 9 8 7 ( 7 8 ) 5 4) - in this example 0 9 8 7 abd 5 4 are top level elements

last function - returns the last element in a list - (last (list 1 2 3 4 5 6 7 8) ) returns 8

nth function - returns the numbered element in a list, the nth functions sees the first element in the list as zero. Thisis recommended (nth 3 (list 9 8 7 6 9) ) returns 6

reverse function - returns a NEW list whose top level elements are in opposite order of which the reverse function was used for. - (reverse (list 6 7 8 9) ) returns ( 9 8 7 6 ) - if you want to change a list to it's reverse you must re-assign what the reverse function outputs. - (setq list_name (list 6 7 8 9 )) - (setq list_name (reverse list_name) )

length function - returns how many top level elements there are in a list - (length (list 1 3 5 7 9)) returns 5

member function - searches a list for a value and returns a new list with the searched value as the first element and the rest of the other elments, - (member 55 (list 44 55 66))returns (55 66)

subst function - return a new list which substitutes one element for another in a list, , it returns a new list, so if you want to change the list you have to setq the list first. - (subst new_value value_to_sub list) - (subst 9 3 (list 1 2 3 4 5) ) will returns (1 2 9 4 5)

acad_strlsort - takes a list of strings and returns that list sorted alphabetically

- (acad_strlsort (list "boat" "apples" "cat") ) returns the list ( "apples" "boat" "cat")

Dotted Pairs - dotted pairs is two item list in which one element is in the Address Register and the other is in the Decrement Register. - created with the cons function - (cons 7 8) returns the dotteed pair (7 . 8) - car returns the first element, cdr returns the the second element

Association lists - is a list made up of many sublists in which the first value of each list represents a numerical key, and the other values in the sublist represent values. If the sublist only has a key and one value then it is a dotted pair, if it has more than one values then it it is a normal lists. - (setq alisst (list ( cons 0 "line") (cons 3 "object" ) (list 5 3.5 9.0) ) ) - will return - (0 . "line") (3 . "object") (5 3.5 9.0)

The assoc functions - is used to extract specific information from an association list - the first argument represents they key that you want to look up and the second one represents the association list you wanna take from. - (assoc key association_list)

- (assoc 5 alist) will return - (5 3.5 9.0)

- so to return the values without the key, use the cdr function

To change association lists - lets say we want to change the value of key 0 in alist, we would use the subst function - remember that subst returns a new list, to change the list you have to reassign it the new list. - (setq alist (subst ( cons 0 "circle") (assoc 0 alist) alist) ) - will return - (0 . "circle") (3 . "object") (5 3.5 9.0)

FILE HANDLING

A computer's ram cannot hold information once the computer is off, so therefore files are used to save information long after the computer has been turned off. AutoLISP has several functions that can read and write to and from files, these files are generally barebones text (ASCII) files.

When AutoLISP creates a file it first creates an empty file on the disk and a memory buffer is made for temporary storage of what is going to go on the file when the memory buffer becomes full. It does this because program would rather deal with ram than disk memory because it is much faster to read and write to.

When AutoLISP read a file it takes a chunk of the file and puts it into a ram buffer so it can read and write faster, when it needs more information from the file the operating system automatically takes the file's content into the ram buffer. AutoLISP doesn't deal directly with files but with ram buffers that are handled directly by the operating system.

When dealing with files on AutoLISP there are three steps you must follow - opening the file, creating the buffer - writing or reading to the buffer - closing the file, flushes the information in the buffer to the file itself, done by the operating system. If you don't close the file the information on the buffer will not be saved or the operating system wont let you edit or delete the file because the buffer still has "dibs" on it.

Sample File Opening/Writing

(setq fw (open "file1.txt" "w")

; the open function returns the memory location of the buffer of the file that will be opened. ; the first argument is the file name ; if you want to open a file in a specific directory you enter the full path and the file name, the directory seperators are a double back-slash. Example ... "c:\\windows\\newfile.txt" ; second argument tells the function what will be done with the file's buffer, ; "w" opens the file for writing ; "a" for appending (writes at the end of the file) ; "r" for reading

(write-line "this is line numero uno" fw)

; the write-line function will write whatever you enter as a string and add a "carriage return" to a memory buffer location, which in this case is stored as fw ; if you want to write to another line you just repeat the function again

; the first argument is the string which will be written ; the second argument is the memory location of the file buffer which you want to write to, which in this case is stored as fw

(close fw)

; this will "flush" or close the buffer which holds the file information and transfer it to the file itself. ; the file was empty in the first two lines, after the third line the file actually gets written to by the operating system.

To read from a file - remember to add the right third argument ( "w" "a" "r") for what you are going to do - use the (read-line buffer_addresss) will read the first line - if you want to read the next line just repeat the function - if you repeat more than the amount of line there are in the text file you will get nil

* when you open a file for reading the information is not removed from the file to the buffer, it is merely copied there, so even after the buffer has been flushed it will still stay the same.

* if you open a file for writing and a file with the same name exists in the disks, the file will be destroyed and written over with new information.

* if you append to a file that doesn't exist it will just be written to with what you append to the beginning of the file.

The getfiled function - (getfiled title default ext flags) - displays a dialog box allows the user to select the name of an existing file or the name of a new file to create, will return the name of the file in the form a string - title : a string which determines the title of the dialog box - default : a default file name to use, or the folder in which to open the dialog box to - ext : the default file name extension , if it a null string it defaults to all file types - flags : 1 = create a new file, 2 disable the "type it button", ...look for more flag descriptions in the help file.

Dealing With Drawing Objects

AutoLISP has the ability to interact with the drawing database through being able to draw and modify entities (lines, arcs, cicles, etc). When you load a drawing all the entities in the database are loaded into memory, they are locoated in the memory by their hex number which is also their entity name. To extract information from an entity you must know it's enttity name (memory location)

The Entlast function - it returns the name of the last entity in the drawing database, it has no arguments - if you just finished drawing a circle, that circle will be at the end of the database, which is what will be returned by the entlast function - useful if you put it right after the program line, where you know what was the last thing that was drawn. - (command .circle p1 dia) - (setq en (entlast)) might return somehing like this... 4ec0ac0 -you now have the name of that entity saved in the variable en.

The entnext function - returns the name of the next entity after the one in the argument of the function - without any arguments it will retrieve the name of the first entity in the database - (entnext en) will return the name of the next entity after the the entity of the argument. - if there are no entities in the drawing it returns nil - you can setup a loop to print out all the entity names in a drawing

(setq en (entnext)) ; set en to the first variable (while (/= en nil) ; while en is not nil (setq en (entnext en) ) ; set en to be the next enttety from the current en (princ en) ; print end (princ "\n") ; add a space to be able to see the entity names better

Selecting Items with the entsel function - the entsel function lets the user pick an object in the drawing and returns a list with the entity name as an item and a point list as the next item which represents the point at which the user selected the entity. - (entsel "prompt") - (setq en (entsel "\nSelect Object" ) ) will return (<Entity Name: 4ec0ac8> ( 5.0 4.0 0) ) - you can extract the point or the entity name by using the list function nth.

(setq g (entsel "\nSelect Object? ") ) (setq name (car g) ) (princ name) (princ "\n") (setq point(cadr g) ) (princ point) (princ "\n")

Creating selection sets with ssget - lets the user create a selection set by any of the selection methods in AutoCAD - since the ssget function does not accept a prompt as an argument, you have to add your own in the form of princ before using the ssget function. - the ssget has many different options to limit the selection look it up in the help file - (princ "\nSelect Items" ) - (setq ss (ssget) ) - Then to extract the individual entities you have to run a loop that involves's the ssname function

The ssname function - extract's the name of an entity from a selection set - the entities in a selection set are ordered from zero and up, - (ssname selection_set number)

The sslength function - returns the number of entities in a selection set - (sslength selection_set)

Extracting the entity names from a selection set with a loop

(setq nuset (ssget)) ; setup nuset as a selection set (setq index -1) ; setuop counter (setq entlist (list nil)) ; set entlist to a null list (repeat (sslength nuset) ; this will repeat by the length of the selection set (setq index (1+ index) ) ;make the counter "count" (setq entlist (cons (ssname nuset index) entlist) ) ; use the ssname function to ;extract the element of the set by the index and add that to entlist )

Extracting an entity's description with entget - it returns a huge association list that contains all the information about the entity - (entget entityname)

Modifying Entities - lets say I setup a line at 0,0 & 2,2

(setq ralf (entget ( car (entsel "select") ) ) ) will return this list... ((-1 . <Entity name: 40068558>) (0 . "LINE") (330 . <Entity name: 4005ecf8>) (5 . "26B") (100 . "AcDbEntity") (67 . 0) (410 . "Model") (8 . "CENTER") (100 . "AcDbLine") (10 0.0 0.0 0.0) (11 2.0 2.0 0.0) (210 0.0 0.0 1.0))

- this represents all of the properties of the line selected, as you can see the sublist with the code 10 and 11 represent the points of the line. So to change the list we used the subst and assoc functions as discussed in the list handling section of my notes. Lets say I want to change the endpoint of the line from 2,2 to 5,5.

- (setq ralf (subst (list 11 5.0 5.0 0.0) (assoc 11 ralf) ralf)

- that just changed the list called ralf, to change the actual entity in the drawing you have to used the entmod function. The only argument it has is the updated list, the list has to be in the same format for endmod to work.

(entmod ralf)

- This will change the endpoint of the line to 5,5

(setq ralf (entget ( car (entsel "select") ) ) ) ;set the list up (setq ralf (subst (list 11 5.0 5.0 0.0) (assoc 11 ralf) ralf)) ;change the list

(entmod ralf) ; change the entity with the changed list

Creating new entities with entmake - the entmake funcion will create a new entity on the drawing from the association list given the associan list you give it as it's argument. The association list can be made from scratch but it is more practical to take a similiar entity's association list and modofiy it to make it. Even though the association list allready has an entity name in their asociation list, entmake will take that whole list and assign it to new entity. - (entmake association_list)

Example

(setq ralf (entget ( car (entsel "select") ) ) ) ;set the list up ; code 1 represents text, coded 10 represents start point, code 40 represents size (setq ralf (subst (cons 1 "Rafael") (assoc 1 ralf) ralf) ); change the text to rafael (setq ralf (subst (cons 40 1.0 ) (assoc 40 ralf) ralf) ); change the text size to 1.0 (setq ralf (subst (list 10 5.0 5.0 0.0 ) (assoc 10 ralf) ralf) ); change the start point to 5,5 (entmod ralf); make the change

Automatic Modifying and Making of entities - I made up these two functions that automate the entity modify and make process, the first argument is the entity name and the second argument is the list that contains the change,

(defun entamake (entity_name change) (setq entity_name (entget entity_name))

(setq entity_name (subst change (assoc (car change) entity_name) entity_name)) (entmake entity_name) )

(defun entamod (entity_name change) (setq entity_name (entget entity_name)) (setq entity_name (subst change (assoc (car change) entity_name) entity_name)) (entmod entity_name) )

Tables

AutoCAD uses table to store information about custom made items that you create, such as layers, custom cordinmate systems, and custom views. Each rows holds an entry and each colum holds a different category.

Various AutoCAD Tables appid block dimstyle style layer ltype ucs identifies loaded applications listing internal blocks in current drawing table of dimensions style settings text style settings layer settings line type settings user cordinate system settings

view vport

different view settings viewport configurations

The tblsearch function - lets the program search for particular enty in a table, the first argument is the table name (string) and the second argument is the name of the entry (string) you are trying to find. If it finds an entry it will return an association list of the enry, if it doesnt find it, it will return nil.

(tblsearch "layer" "hidden" ) will return ((0 . "LAYER") (2 . "HIDDEN") (70 . 0) (62 . 80) (6 . "HIDDEN"))

This is an overview of the codes in the layer list code0 code2 code6 code62 code70 name of table name of layer line-type color number status flags, (bitwise) 1frozen 4locked

(tblsearch "style" "standard") will return ((0 . "STYLE") (2 . "Standard") (70 . 0) (40 . 0.125) (41 . 1.0) (50 . 0.0) (71 . 0) (42 . 0.125) (3 . "txt.shx") (4 . ""))

code0 code2

name of table name of textstyle

code3 code40 code41 code42 code50

name of font file textheight (0 = variable, non-zero fixed height) color number last height used oblique angle.

Using the tblnext function with a loop to get every entry in a tablee

-tblnext funtion accepts the table name as argument. It will return information on the next entry in the table, if you execute it again it will do it for the next entry over and over again until there are no more entries in which it will return nil. If you put a 1 as a second argument it will "rewind" and return the first entry

(print (tblnext "layer" 1)) ; first to rewind to the first entry (while (print (tblnext "layer"))) ; then this will keep printing the function until it prints nil

Selection Sets

The ssget Function - holds objects that can be used to gather entities, and used to reply to prompts that asks for selections (ssget [sel-method] [pt1 [pt2]] [pt-list] [filter-list]) - sel-method, string that determines how objects are selected L last visible entities added to the database

P X

last selection set created entire selection, will select all entities in database

- filter-list, an association list that designates what entities should be added to the set, any objects that have an association list which contain the argument sublist will be added to the set. For example (ssget "x" (list ( cons 0 "line") (cons 8 "hidden )) ) - will return you a selection set that contains all the lines which belong to layer "hidden" drawing. This can only be used to filter out one type of object, you cannot setup an ssget function for example that would select lines and ellipses only.

The ssname function - returns the entity name of a given element in a selection set. (ssname selection_set index) - index represents the order of the item in the selection set, STARTS WITH ZERO - you can create an iteration that will return all the entity names within a selection set. (setq nuset (ssget)) ; setup nuset as a selection set (setq index -1) ; setuop counter (setq entlist (list nil)) ; set entlist to a null list (repeat (sslength nuset) ; this will repeat by the length of the selection set (setq index (1+ index) ) ;make the counter "count" (setq entlist (cons (ssname nuset index) entlist) ) ; use the ssname function to the element of the set by the index and add that to entlist ) -returns nil if index is negative or larger than what the selection set has ;extract

* Remember objects from sseget are added in this order, the newest object is added first and is at index 0, the oldest object created is at the highest index.

The ssadd function - adds an element to an existing or new selection set (ssadd entity_name selectionset) - if you use it withou any arguments it will create an empty selection set - if you just use the entity_name argument it will return a new selection set with that entity in it.

ssdel function - removes an entity from a selection set and returns the newly modified selection set (ssdel entity_name selection_set)

sslength - returns the number of entities in a selections set, as an integer (sslength selection_set)

ssmemb - tests to see if a specified entity is in a selection set, returns the entity name if it does exist in the selection set (ssmemb entity_name selection_set)

AutoLISP Tips

* If you want a code routine to load up automatically with AutoCAD, put it in autocad200.lsp in the support directory of your install directory.

* It is better to make text in AutoLISP through the use of the .mtext command because it is much easier to control the placement of the text. Where all you have to do is find out points for the start and end points that define the mtext box and then define the size and it's justification through the command. As in when you are using the .text command it might be harder to place text that you want to be justified as middle-center and you also have to deal with the setting up of modifying of text styles. With mtext you specify the size, font justification through the command itself.

* Osnap modes are dangerous when drawing pbjects because the mouse might mess what points are chosen when objects are drawn. So control osnap that in a way that it is only turned on when needed and turned off when it isn't needed anymore. For example, you should enable osnap when selecting a point, and right after it's selected you turn it off.

* Remember to save the osnap and layer settings to what they were before the program is run.

* When trying to locate points that are not linearly displaced from each other, and the trigonometric functions would be too complex, use a combination of the inters, polar, distance functions to locate the point you want to find.

Radians

AutoLISP use radians to calculate angles, so every angle in degrees should be converted to radians. Degrees-Radians Radians-Degrees Degrees * (pi/180) Radians * (180/pi)

pi/180

=0 .25pi = 45

.5pi .75 pi

= 90 = 135 = 180 1.25pi = 225

1.5pi

= 270 1.75pi = 315

2pi

= 300

Or instead of dealing with that you can setup a quick function in the begining of the lisp file that will convert degrees to radians, and you will never deal with them again. Notice that I used ":" as the variable symbol. Just type (: 180) and it will return you the angle in radians

(defun : (deg)(* deg (/ pi 180)))

Bitwise systems

Each number represents a certain property, if you want to combine two different properties you add the two number to get the new combined property. For example the variable osmode which controls what osnaps are enable are controlled by bitwise controls.

0 NONe 1 ENDpoint 2 MIDpoint 4 CENter

Each of these numbers represents an osmode option, but if want to combine different modes such as only enabling endpoint and centerpoint object snaps I would use 5 ( 1 + 4)

(setvar "osmode" 5)

Data Types Conversion & Handling

ename

entity names, numeric table assigned to objects within AutoCAD, it is a pointer that refers to an object with an AutoCAD file, and can be used to find the objects database record and it's vectors. <Entity name: 27f0540>

list

lists, groups of values enclosed and grouped together (list value1 value 2 ....) (list 0 0 4) 5 6 7

int

integers , whole numbers that do no use decimal points 5 125 69875112

real

floating-point numbers, a number that contains a decimal they are provided with 14 decimal places of precision 5.25 0.15

str

strings, group of data surrounded by quotations "" "This is a string"

sym

symbols, are used to refer to static data such as functions *)(

* In arithmetic function , if all arguments are integers then the value returned is an integer. If you have a real number in your argument then the value returned will be a real. Take notice not to divide 1 by 2, those are integers and the answer for that is a decimal, it will give you zero, it will mess your program up. - when submitting arguments to a function you must check to see if they are of the right data type, you canot submit strings to arithmetic functions for instance. It will return a "bad data-type " error.

- to know what type of data a variable is try (type variable), it will return the symbol type

String Functions

String Length - returns an integer that represents the amount of characters in a string

(strlen "string")

String Concatenation- joins two or more strings into one (strcat "string_1" "string_2")

Extracting a substring from a string, depending on the start character no and the end character number. (sbstr "string" character_no_start character_no_end)

Ex. (setq a "Hello") (setq c (substr a 3 5)) (princ c)

Returns "llo"

Convert to upper/lower case, putting a 1 as argument determines what to convert to. (strcase "string" 1) converts to uppercase (strcase string)

Conversion of Data Types

Integer to String (itoa integer)

Converting real to strings (rtos number mode precison)

- number, the number you will convert - mode, sets the format of the number in the string 1 for scientific, 2- decimal, 3

- engineering, 4 architectural, 5 fractional. If the argument is ommited, it will use ACADS LUNITS system variable for the mode.

- precision- the amount of decimal places the string number will have. Corresponds to AuotCAD's LUPREC varibale so if nothing is put there it will use the LUPREC value in place of that..

(setq a (rtos 0.0625 4)) ;.... converts .0625 to a fractional string.

String to Real number (atof "string" ) - string must not contain any spaces

Displaying Text in the Prompt

The princ functions prints both strings and numerical values without conversion, and it uses control characters such as "/n" instead of printing them.

Control characters - must be included in the quotation marks

-If you want to make sentences that are mixed with variables you would do it by repeating the princ for example to print "The diameter of the hole is 5 you woudl do so by typing this

(Princ "The Diameter of the hole is") (Pinc dia)

- To skip a line... type (princ "/n")

Control Characters \n carriage return and line feed (new line) \r carriage return only (cursor stays on same line) \t tab every 8 columns (9th, 17th, 25th, etc.) \\ single backslash (useful for path names - or, a single forward slashes can be used in path names)

\e escape character (useful for sending escape codes to a printer, etc.) \xxx character whose octal (base 8) code is xxx

Errors - and what they probably mean

malformed list on input - your probably missing a parenthesis

misplaced dot on input - you forgot to put a leading zero on decimal

argument type: numberp: nil - there is a variable that doesnt have a value, or isn't compatible with the function. Check your variable ype and check the refference for the function explanation to see what data types it will accept

Overall program writting tips

- first do a program with your own variables, when that works add a user input section - seperate operations section from display sections - first do the program as is, then add the function defining parameters at the end. - when writting a program with many choice driven subroutines, first build the base

AutoCAD's Visual Lisp Editor Tips - double click in front of or behind a parenthesis so that the program will highlist all the content that falls within it's matching parenthesis. If you hear a sound it's because it doesnt have a mathching parnethesis, which you should check out what's going on. - use the format selection button button ( a triangle with parenthesis ) so that the program will automatically put indents so that matching parenthesis share the same columns.

Vous aimerez peut-être aussi