Elisp: Variable
Global Variables
setq
-
(setq var value)
(setq var1 value1 var2 value2 etc)
Set one or more variables. Return the last value.
Each pair of variable value are evaluated in order. Latter expressions can contain earlier variable.
;; assign 3 to x ;; return the value (setq x 3)
;; multiple assignment ;; return the last value (setq xa 1 xb 2 xc 3)
;; multiple assignment. later values can contain earlier var (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 (var1 var2 etc) body)
each of the form var can also have the form
(var value)
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.(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
, andsetq
.
Advanced Variable Binding Forms
These are advanced, and rarely used.
letrec
dlet
named-let