Elisp: Variable

By Xah Lee. Date: . Last updated: .

Global Variables

setq
  • (setq var val)
  • (setq var1 val1 var2 val2 etc)

Set one or more variables. Return the last value.

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

;; 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 var
(equal
 (setq xa 1
       xb (+ xa 3))
 4)
defvar
(defvar name &optional INITVALUE DOCSTRING)

Declare and assign a variable, and return the symbol name.

💡 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

let
(let VARLIST BODY...)

(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
 )

💡 TIP: I recommend not to use this. Because when you have many variables, its harder to tell which are dependent on which. Simply use let, and setq.

More Local Variable Functions

these are more advanced function for local variables, and rarely used.

Reference

Elisp, Variable