setq
setq Special Form
Syntax:
setq {↓pair}* → result
pair::=var form
Pronunciation:
[ set kyu- ]
Arguments and Values:
var—a symbol naming a variable other than a constant variable.
form—a form.
result—the primary value of the last form, or nil if no pairs were supplied.
Description:
Assigns values to variables.
(setq var1 form1 var2 form2 ...) is the simple variable assignment statement of Lisp. First form1 is evaluated and the result is stored in the variable var1, then form2 is evaluated and the result stored in var2, and so forth. setq may be used for assignment of both lexical and dynamic variables.
If any var refers to a binding made by symbol-macrolet, then that var is treated as if setf (not setq) had been used.
Examples:
;; A simple use of SETQ to establish values for variables.
(setq a 1 b 2 c 3) → 3
a → 1
b → 2
c → 3
;; Use of SETQ to update values by sequential assignment.
Data and Control
(setq a (1+ b) b (1+ a) c (+ a b)) → 7
a → 3
b → 4
c → 7
;; This illustrates the use of SETQ on a symbol macro.
(let ((x (list 10 20 30)))
(symbol-macrolet ((y (car x)) (z (cadr x)))
(setq y (1+ z) z (1+ y))
(list x y z)))
→ ((21 22 30) 21 22)
Side Effects:
The primary value of each form is assigned to the corresponding var.
See Also:
psetq, set, setf
Expanded Reference: setq
Simple variable assignment
setq assigns a value to a variable and returns the assigned value.
(defvar *x*)
=> *X*
(setq *x* 42)
=> 42
*x*
=> 42
Multiple sequential assignments
setq can assign to multiple variables in sequence. Each assignment completes before the next form is evaluated.
(let (a b c)
(setq a 1 b 2 c 3)
(list a b c))
=> (1 2 3)
Sequential evaluation means later assignments see earlier ones
Because pairs are processed left to right, later values can depend on earlier assignments.
(let ((a 0) (b 0))
(setq a 10 b (+ a 5))
(list a b))
=> (10 15)
Assigning to lexical variables inside let
setq works with lexical variables created by let, not just special variables.
(let ((count 0))
(dotimes (i 5)
(setq count (+ count i)))
count)
=> 10
Returns the value of the last assignment
When given multiple pairs, setq returns the value of the last form.
(let (x y)
(setq x 'first y 'second))
=> SECOND
setq with no pairs returns NIL
(setq)
=> NIL