Emacs Lisp: Variable

By Xah Lee. Date: . Last updated: .

Global Variables

setq
  • (setq SYM VAL)
  • (setq SYM1 VAL1 SYM2 VAL2 etc)

Set one or more variables. Return the last value.

SYM should not be quoted. setq (setq x 3) is short for (set (quote x) 3)

Each pair of sym val are evaluated in order. Latter expressions can contain earlier symbols.

;; assign 3 to x
;; return the value
(setq x 3)
(equal x 3)
;; multiple assignment
;; return the last value
(equal
 (setq xa 1 xb 2 xc 3)
 3)
;; multiple assignment. later values can contain earlier symbols
(equal
 (setq xa 1
       xb (+ xa 3))
 4)
defvar
(defvar SYMBOL &optional INITVALUE DOCSTRING)

Declare and assign a variable, and return the SYMBOL.

💡 TIP: this is mostly used for packages. When writing a package, you should declare variables. This way, it has a docstring.

(defvar xx 4 "DOCSTRING")

Local Variables

To define local variables, use let. The form is:

(let (var1 var2 etc) body)

each of the form var can also have the form

(var val)

Each variable by default has value of nil.

The body is one or more lisp expressions. The body's last expression's value is returned.

(let (a b)
 (setq a 3)
 (setq b 4)
 (+ a b)
) ;  7
(let ((a 3) (b 4))
 (+ a b)
) ;  7
let*
like let, but latter expression can contain symbols defined earlier.
(equal
 (let* ((xa 3)
        (xb xa))
   xb
   )
 3
 )

Reference

Emacs Lisp Variable