In Emacs Lisp, how do I check if a variable is defined?

EmacsLispElisp

Emacs Problem Overview


In Emacs Lisp, how do I check if a variable is defined?

Emacs Solutions


Solution 1 - Emacs

you may want boundp: returns t if variable (a symbol) is not void; more precisely, if its current binding is not void. It returns nil otherwise.

  (boundp 'abracadabra)          ; Starts out void.
  => nil

  (let ((abracadabra 5))         ; Locally bind it.
    (boundp 'abracadabra))
  => t

  (boundp 'abracadabra)          ; Still globally void.
  => nil

  (setq abracadabra 5)           ; Make it globally nonvoid.
  => 5

  (boundp 'abracadabra)
  => t

Solution 2 - Emacs

In addition to dfa's answer you may also want to see if it's bound as a function using fboundp:

(defun baz ()
  )
=> baz
(boundp 'baz)
=> nil
(fboundp 'baz)
=> t

Solution 3 - Emacs

If you want to check a variable value from within emacs (I don't know if this applies, since you wrote "in Emacs Lisp"?):

M-: starts Eval in the mini buffer. Write in the name of the variable and press return. The mini-buffer shows the value of the variable.

If the variable is not defined, you get a debugger error.

Solution 4 - Emacs

Remember that variables having the value nil is regarded as being defined.

(progn (setq filename3 nil) (boundp 'filename3)) ;; returns t

(progn (setq filename3 nil) (boundp 'filename5)) ;; returns nil

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmikeView Question on Stackoverflow
Solution 1 - EmacsdfaView Answer on Stackoverflow
Solution 2 - EmacsJacob GabrielsonView Answer on Stackoverflow
Solution 3 - EmacsGauthierView Answer on Stackoverflow
Solution 4 - EmacscjohanssonView Answer on Stackoverflow