Variables, setq, & formulas |
![]() |
What are variables?
A variable is a symbol that temporarily holds (actually, points to) information. The information is stored so that it can be retrieved later in the program. Each time the program is run, the variable might hold different information. In fact, a variable might hold many different values within a single running of a program. (That's why they are called variables!)
Variables in AutoLISP are similar to variables in algebra or in a formula. For example, in the equation y = 3x - 5, the variable x holds different numbers at different times and, of course, so does y. In the formula area = length x width, all three words are variables, taking on different values in different situations. Variables can be contrasted with constants, such as 3 and 5.
Variables are assigned values. In the case of a formula, this assignment takes place when you rewrite the formula and put a particular value in place of the variable. In a sense, it is assigned simply by substitution. In AutoLISP, variables are assigned values by the setq function, as described below. (Actually, there are several other ways of assigning values to variables which will be covered in later lessons, but the setq function is the most basic. So we will concentrate on setq in this lesson.)
After a variable is assigned a value, that value is available to be retrieved (or in programming lingo, accessed or referenced). You can see what value is in a variable by dumping it to screen. This is done at the AutoCAD command prompt by typing an exclamation point (!) followed immediately by the variable name. For example, suppose the variable x has been assigned the value 25.75. When you enter !x AutoLISP dumps 25.75.
Naming variables
As a general rule, a variable will usually begin with a letter, contain several letters (preferably lower case) or numbers, and remind you of the type of value it holds. Here are several variable names which follow this general rule:
point1, point2, p1, p2, len, width, height, x, y, z, var1, var2, side1, side2
Technically, variables can be any length and can contain any combination of characters except: ( ) . ' " ; This means that, if you are nuts, you can use some rather bazaar looking variable names such as $%@#! or -*_*-. But who wants to type garbage like that? Also, a variable must contain more than just numbers otherwise the AutoLISP interpreter would read it as a number rather than a variable.
Variable names are not case sensitive. In fact, when AutoLISP dumps programming code to the screen after an error, you will notice that all variables (and other symbols) are displayed in upper case. However, most programmers use lower case for variables, in fact, for nearly all AutoLISP code, and you should do the same.
Don't give variables names that are already used by pre-assigned variables such as t, nil, pause, and pi.
Don't give variables names that are already used by built-in functions. For example, many programs deal with dimensions such as length, width, height, etc. But since there is a built-in function called length, you would not want to use length as a variable name. Similarly, many programs deal with certain types or kinds of items. But since there is a built-in function called type, you would not want to use type as a variable name. Using such a name would reassign that symbol a different value and thus disable the function. The names of built-in functions and pre-assigned variables are sometimes called "reserved words" or "reserved symbols."
After you are an experienced AutoLISP programmer you will know what symbol names to avoid. But in the mean time, there is a simple way to find out if a particular name is already taken. At the AutoCAD command prompt, dump the name (type an exclamation point and the variable name, as explained in the previous section). If AutoLISP dumps nil, then that name is not pre-assigned. But if AutoLISP dumps something that looks like this <Subr: #xxxxxxx> then you know it is a built-in function (subroutine) and should not be used as a variable name.
How long should a variable name be? Variables that are 3 to 6 characters long are easy to work with. They should be long enough to remind you what the variable stands for, but short enough to type easily. On the one hand, you can use single letters, such as a, b, c, x, y, z, etc. as variables, but that is not always best. Single-character variables can become a hassle should you decide to change a variable name as a program evolves (many text editors will replace more than you bargained for). You might recall that we used very short variable names in our first few sample programs. But that was only because people are used to seeing short variables in equations and formulas and we wanted those first programs to be easy for the beginner to read. On the other hand, you can use long variable names, such as length-of-arm or default_radial_increment. But if all your variables are this long, your program will be more difficult to write and debug. Half of your program may extend past the right side of the screen. You might wear the letters off your keyboard. And you will probably produce more than your usual share of typos.
The setq function
The setq function assigns values to variables. In the following sample, the value 1.5 is assigned to variable dia (short for diameter).
(setq dia 1.5)
The syntax is simple. The first argument is the variable name, the second argument is the value to be assigned. After the assignment is made, the setq function returns the value that it assigned, which is displayed on screen.
You can make more than one assignment as illustrated below.
(setq num1 55.3 num2 66.4 str1 "doo" str2 "daa")
The syntax is still simple. For each pair of arguments, the first in the pair is the variable, the second in the pair is the value to be assigned. Obviously, setq must always have an even number of arguments. When setq makes multiple assignments, it returns only the last value that it assigns, which in the above case would be "daa".
The function name "setq" stands for set-quote. It always quotes the variable name rather than evaluating it. In most cases, when a variable appears in an expression, its value is retrieved and then used in some way (perhaps in a calculation). In other words, the variable is evaluated. But here we do not want the variable to be evaluated, we want it to be assigned a value (or in technical terms, bound to a value). There is another function, set, which does not quote the variable. If we were to use set to assign a value to a variable, we would have to use an expression involving either the quote function or the single quotation mark like one of the following:
(set (quote dia) 1.5) -or- (set 'dia 1.5)
And if we were assigning several variables, each one would have to be quoted. You can see that the setq function is more convenient (at least, more convenient than using the set function with the quote function). Also, setq is the customary function to use when making simple assignments.
How long does a variable keep its value?
If you stay in the same drawing, a variable will keep its value until it is assigned a different value. This might happen within the running of a particular program, where a variable is assigned several different values during the course of the program. In fact, if a variable is in a loop (a repeating section of a program) it may be reassigned different values in rapid succession.
If the variable is a local variable, it will lose its value as soon as the program quits. (More on global and local variables in a later lesson).
Even if a variable is global and it retains its value after the program quits, it may loose its value as soon as a new drawing is opened (or the same drawing reopened). This depends on the setting of the system variable LISPINIT.
By the way, LISPINIT applies to all AutoLISP symbols, including pre-assigned variables, built-in function names, and functions you have defined and loaded into AutoCAD. So if you accidentally disable a built in function or assign a bogus value to pi, you can set LISPINIT to 1 then re-open the current drawing.
Practice session
Here are just a few expressions using setq that you should type at the command prompt. In each case, notice what the setq function returns. Then, use the exclamation point (!) to dump the values in the variables you have assigned, just to check. Also make up several of your own.
(setq num1 12.34)
(setq num2 (* 10 num1))
(setq len 18 wid 12 hei 6)
(setq perim (+ len wid))
(setq vol (* len wid hei))
(setq density (* vol 0.26))
(setq adults 101 children (* 1.4 adults))
NOTE: What follows are examples of what you should not do, normally. They are included here just to reinforce a point made earlier. We will "accidentally on purpose" change the multiplication (*) function and disable the setq function, then restore them both.
(setq * -)
(* 6 3) -- Notice that instead of returning 18, * now returns 3 because the symbol "*" has been reset to the subtraction subroutine.
(setq setq 4)
(setq num 10) -- Produces an error message because the first item in this list no longer points to the setq subroutine, it points to the number 4.
To restore both * and setq, set system variable LISPINIT to 1 then re-open the drawing. Test both functions to make sure that they have been reset. (If, for some reason, these two functions have not been restored, exit AutoCAD altogether, then restart AutoCAD.)
Converting formulas to AutoLISP expressions.
Here are some formulas given in both algebraic notation and AutoLISP notation. Study both versions of the formulas until you are sure you understand why the AutoLISP expression accomplishes the same thing as the algebraic formula.
Algebraic formula | AutoLISP expression |
1. Area of triangle Area = bh/2 |
(setq area (/ (* base hei) 2.0)) [hei = height] |
2. Area of circle Area = πr2 |
(setq area (* pi rad rad)) [rad = radius] |
3. Volume of cylinder Volume = πr2h |
(setq vol (* pi rad rad hei)) [vol = volume, rad = radius, hei = height] |
4. Volume of sphere Volume = (4/3)πr3 |
(setq vol (/ (* 4 pi rad rad rad) 3)) [vol = volume, rad = radius] |
5. Pythagorean theorem c = (a2 + b2)½ |
(setq c (sqrt (+ (* a a) (* b b)))) [c = hypotenuse, a = side a, b = side b] |
6. Fahrenheit F = (9/5)C + 32 |
(setq far (+ (* 1.8 cel) 32)) [far = Fahrenheit, cel = celsius] |
7. No. of studs for wall length (16" centers) Studs = 2 + (length - 2)/16 (ignore fraction of stud) |
(setq studs (+ 2 (/ (- len 2) 16))) [len = length of wall to nearest inch, must be an integer] |
Another practice session
Test each of the formulas in the table above. First, use setq to assign values to the variables. Then enter the AutoLISP expression in the right-hand column. The setq function will return the answer as well as assign it to the appropriate variable. Thus, the answer will be displayed as soon as you enter the final closing parenthesis. In addition, you will be able to display the answer by dumping the value in the appropriate variable. For example, for the first formula use setq to assign values to variables base and hei. Then enter the expression (setq area (/ (* base hei) 2.0)) Notice what the expression returns, and dump the value in variable area.
Here are some additional formulas for you to translate into AutoLISP expressions and then test. Be careful with numbers 5 and 6 below. For example, number 5 contains the same letter representing one thing when upper case, and another when lower case. Since AutoLISP variables are not case sensitive, an upper case variable is the same as a lower case. You will have to distinguish between the two in a different way, perhaps by using orad for outside radius and irad for inside radius. (Notice that we avoided suggesting or and ir because or is a built-in function.)
1. E = IR Ohm's law (E = voltage, I = current, R = resistance)
2. A = (b1 + b2)h/2 Area of trapezoid (b1 and b2 are bases, h = height)
3. V = b2h/3 Volume of a pyramid (b = length of base, h = height)
4. C = (5/9)(F - 32) Celsius (F = degrees Fahrenheit)
5. V = πh(R + r)(R - r) Volume of hollow cylinder, such as the volume of metal in an iron pipe (R = outside radius, r = inside radius)
6. N = 0.907((D/d) - 0.94)2 + 3.7 Number of inscribed equal tangent circles that will fit in a larger circle (D = dia. of large circle, d = dia. of small circles)
7. x = (-b ±(b2 - 4ac)½)/ 2a The Quadratic formula for an equation in the form ax2 + bx + c = 0. Since the square root section of this formula is plus-or-minus, you will have to write one AutoLISP expression for the plus and a separate expression for the minus.
Sample program, ba (bend allowance)
This program calculates bend allowance, that is, the developed (flat) length of a bent section of sheet metal before it is bent. The bend allowance is equal to the length of the neutral arc, which can be calculated from the material thickness (T), inside radius of the bend (R), and the number of degrees through which the material is bent (A).
The bend allowance for any bend is the length of the neutral arc (the arc in a side view of the bend representing the plane of material that is neither stretched nor compressed. The length of this plane (the length of the arc in the side view, as shown above) is the same before and after bending.
This plane occurs a certain fraction of the thickness into the material from the inside radius. This fraction usually ranges between 1/4 and 1/2, but is never greater than 1/2. For rough calculations, a fraction of 1/3 is often used for all bends. However, the fraction actually varies from one bend to the next because the fraction depends on the ratio between the size of the inside radius and the thickness of the material. The fraction moves from 1/2 toward 1/4 as the radius gets smaller or the material gets thicker. The following formula provides a fraction (F) that agrees with most reference books reporting experimental results.
F = (R/T)/16 + 0.25 (F never greater than 0.5)
Note that line 8 of the program calculates F (frac), and line 9 checks to make sure it is not over 0.5 (if it is, it is reset to 0.5). More will be explained about the use of the if function in a later lesson.
After F is determined, the formula used to calculate the bend allowance is
BA = pA(R + FT) / 180
An enhanced version of this program (including default prompts and an error routine) is found in Lesson 15.
Instructions for trying this program are found under "Introduction" in "Fifteen Lessons."
------ marker ------ beginning of working program ------ try it out ------
;| BA, short for Bend Allowance
Copyright © 1988,Ronald W. Leigh
Input: Material thickness, inside radius, angle
Output: Developed length of neutral arc
Variables:
ang Angle
frac Fraction of thickness, from irad to neutral
arc
irad Inside radius
lona Length of neutral arc
thick Material
thickness
|;
(defun c:ba (/ ang frac irad lona
thick)
;line 1
(initget
7)
;line 2
(setq thick (getreal "\nMaterial thickness:
"))
;line 3
(initget
5)
;line 4
(setq irad (getreal "\nInside radius:
"))
;line 5
(initget
7)
;line 6
(setq ang (getreal "\nAngle:
"))
;line 7
(setq frac (+ (/ irad thick 16)
0.25))
;line 8
(if (> frac 0.5) (setq frac
0.5))
;line 9
(setq lona (/ (* pi ang (+ irad (* frac thick))) 180)) ;line 10
(princ "\nBend allowance =
")
;line 11
(princ
lona)
;line 12
(princ)
;line 13
)
;line 14
--------
marker
-------- end of working program -------- try it out --------