Node:Counting, Previous:Using setq, Up:set & setq



1.9.3 Counting

Here is an example that shows how to use setq in a counter. You might use this to count how many times a part of your program repeats itself. First set a variable to zero; then add one to the number each time the program repeats itself. To do this, you need a variable that serves as a counter, and two expressions: an initial setq expression that sets the counter variable to zero; and a second setq expression that increments the counter each time it is evaluated.

(setq counter 0)                ; Let's call this the initializer.

(setq counter (+ counter 1))    ; This is the incrementer.

counter                         ; This is the counter.

(The text following the ; are comments. See Change a Function Definition.)

If you evaluate the first of these expressions, the initializer, (setq counter 0), and then evaluate the third expression, counter, the number 0 will appear in the echo area. If you then evaluate the second expression, the incrementer, (setq counter (+ counter 1)), the counter will get the value 1. So if you again evaluate counter, the number 1 will appear in the echo area. Each time you evaluate the second expression, the value of the counter will be incremented.

When you evaluate the incrementer, (setq counter (+ counter 1)), the Lisp interpreter first evaluates the innermost list; this is the addition. In order to evaluate this list, it must evaluate the variable counter and the number 1. When it evaluates the variable counter, it receives its current value. It passes this value and the number 1 to the + which adds them together. The sum is then returned as the value of the inner list and passed to the setq which sets the variable counter to this new value. Thus, the value of the variable, counter, is changed.