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

25,161

Solution 1

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

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

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

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
Share:
25,161

Related videos on Youtube

mike
Author by

mike

Updated on July 08, 2022

Comments

  • mike
    mike almost 2 years

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

  • Rainer Joswig
    Rainer Joswig about 15 years
    sometimes it might also be useful to use INTERN-SOFT to check whether a symbol exists.
  • Radon Rosborough
    Radon Rosborough over 7 years
    Equivalently, M-: (boundp 'the-variable-name) RET will check without the need for triggering an error.
  • binki
    binki almost 7 years
    I'm pretty sure the question is about elisp scripts, not the interactive UI of Emacs.
  • Dhawan Gayash
    Dhawan Gayash over 3 years
    I also sometimes use symbol-value function to print the actual value. symbol-value-doc. Egs: Using the eval-expression command and then typing this out: (symbol-value 'abracadabra)
  • HappyFace
    HappyFace almost 3 years
    The let block returns nil for me. Does this work with lexical binding?