What is the difference between setq
and defvar
in Emacs lisp?
I see common lisp version of the same question at https://stackoverflow.com/questions/3855862. Are they same in Elisp?
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.
Sign up to join this communityWhat is the difference between setq
and defvar
in Emacs lisp?
I see common lisp version of the same question at https://stackoverflow.com/questions/3855862. Are they same in Elisp?
You should ask Emacs this question: C-h i
, choose the Elisp manual (m Elisp
), and search the index for "defvar" (i defvar
). That takes you to node Defining Variables.
Emacs tells you that defvar
allows attaching a doc string, and that if the variable already has a value then it does nothing.
It also tells you about the use of defvar
with no value to be assigned: (defvar foo)
. It tells you that that declares the variable to be dynamically scoped.
setq
has none of those properties.
defvar
and setq
are similar, but not quite the same, in Emacs Lisp and Common Lisp.
defvar
is a global variable (as in imperative programming style) and a convention for customization, while setq is more like a let binding in functional programming languages (with dynamic/lexical scoping rule depending of which global scoping mode is active.........)
– nicolas
Dec 1 '18 at 11:04
setq
sets a var value, regardless of whether the var (occurrence) is local. defvar
declares a var as global. (It may also be "buffer-local": local-variable-p
.) A var occurrence bound as a function arg or by let
is "local" in the usual sense. If a var bound by let
etc. is global (or buffer-local) then a local binding (usual sense) is created for it, for the duration/scope of that let
. Within that binding scope, setq
changes the local value. It's better to talk about a var occurrence being local (on stack) or global (on heap) than a var being so.
– Drew
Dec 1 '18 at 18:22
M-x report-emacs-bug
to suggest improvements that might help others get it easier.
– Drew
Dec 1 '18 at 20:21