Next: , Previous: , Up: Variables   [Contents][Index]


5.8.2 Setting Variables

Setting a variable means to overwrite its current value (that is, the value of its most recent active binding) with a new one. In the variable-as-stack analogy, this is analogous to overwriting the top of the stack. The old value is irretrievably lost (unlike when a new value is bound to a variable, see Local Variables).

The setq special form is the usual method of altering the value of a variable.

Special Form: setq variable form …

Each variable is set to the result of evaluating its corresponding form. The last value assigned becomes the value of the setq form.

(setq x 20 y (+ 2 3))
    ⇒ 5

In the above example the variable x is set to 20 and y is set to the value of the form (+ 2 3) (5).

Function: set variable new-value

The value of the variable variable (a symbol) is set to new-value and the new-value is returned.

This function is used when the variable is unknown until run-time, and therefore has to be computed from a form.

(set 'foo 20)
≡
(setq foo 20)           ;setq means `set-quoted'
    ⇒ 20

Note: currently the set function may be used to set any type of variable (i.e. lexical or special). However this likely to change in the future, such that only special variables will be allowed to be modified using the set function. It is strongly advised to avoid using this function on lexical bindings! (Moreover the compiler may generate incorrect code in certain circumstances.)


Next: , Previous: , Up: Variables   [Contents][Index]