Next: Variable Scoping, Previous: Accessing Variables, Up: Variables
The usual way to change the value of a variable is with the special
form setq. When you need to compute the choice of variable at
run time, use the function set.
This special form is the most common method of changing a variable's value. Each symbol is given a new value, which is the result of evaluating the corresponding form. The most-local existing binding of the symbol is changed.
setqdoes not evaluate symbol; it sets the symbol that you write. We say that this argument is automatically quoted. The `q' insetqstands for “quoted.”The value of the
setqform is the value of the last form.(setq x (1+ 2)) => 3 x ;xnow has a global value. => 3 (let ((x 5)) (setq x 6) ; The local binding ofxis set. x) => 6 x ; The global value is unchanged. => 3Note that the first form is evaluated, then the first symbol is set, then the second form is evaluated, then the second symbol is set, and so on:
(setq x 10 ; Notice thatxis set before y (1+ x)) ; the value ofyis computed. => 11
This function sets symbol's value to value, then returns value. Since
setis a function, the expression written for symbol is evaluated to obtain the symbol to set.The most-local existing binding of the variable is the binding that is set; shadowed bindings are not affected.
(set one 1) error--> Symbol's value as variable is void: one (set 'one 1) => 1 (set 'two 'one) => one (set two 2) ;twoevaluates to symbolone. => 2 one ; So it isonethat was set. => 2 (let ((one 1)) ; This binding ofoneis set, (set 'one 3) ; not the global value. one) => 3 one => 2If symbol is not actually a symbol, a
wrong-type-argumenterror is signaled.(set '(x y) 'z) error--> Wrong type argument: symbolp, (x y)Logically speaking,
setis a more fundamental primitive thansetq. Any use ofsetqcan be trivially rewritten to useset;setqcould even be defined as a macro, given the availability ofset. However,setitself is rarely used; beginners hardly need to know about it. It is useful only for choosing at run time which variable to set. For example, the commandset-variable, which reads a variable name from the user and then sets the variable, needs to useset.Common Lisp note: In Common Lisp,setalways changes the symbol's “special” or dynamic value, ignoring any lexical bindings. In Emacs Lisp, all variables and all bindings are dynamic, sosetalways affects the most local existing binding.