[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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
.
setq
does not evaluate symbol; it sets the symbol that you
write. We say that this argument is automatically quoted. The
`q' in setq
stands for "quoted."
The value of the setq
form is the value of the last form.
(setq x (1+ 2)) => 3 x ; |
Note 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 that |
set
is 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) ; |
If symbol is not actually a symbol, a wrong-type-argument
error is signaled.
(set '(x y) 'z) error--> Wrong type argument: symbolp, (x y) |
Logically speaking, set
is a more fundamental primitive than
setq
. Any use of setq
can be trivially rewritten to use
set
; setq
could even be defined as a macro, given the
availability of set
. However, set
itself 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 command
set-variable
, which reads a variable name from the user and then
sets the variable, needs to use set
.
Common Lisp note: In Common Lisp,set
always changes the symbol's "special" or dynamic value, ignoring any lexical bindings. In Emacs Lisp, all variables and all bindings are dynamic, soset
always affects the most local existing binding.
One other function for setting a variable is designed to add an element to a list if it is not already present in the list.
The argument symbol is not implicitly quoted; add-to-list
is an ordinary function, like set
and unlike setq
. Quote
the argument yourself if that is what you want.
Here's a scenario showing how to use add-to-list
:
(setq foo '(a b)) => (a b) (add-to-list 'foo 'c) ;; Add |
An equivalent expression for (add-to-list 'var
value)
is this:
(or (member value var) (setq var (cons value var))) |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |