1

I am new to Emacs-Lisp and I was surprised to learn a curious variable scoping rule in Emacs that any variables which are intended to be used locally must be explicitly declared with let. Otherwise variables set with setq get global scope. to be precise here is some code.

e.g.

;; outside this function foo1 and bar1
;; don't exist. 
(defun add1 ()
  (let ((foo1 1) (bar1 4))
    (+ foo1 bar1)))

;; but here without the let-statements the
;; variables persist!
(defun add2()
  (setq foo2 1)
  (setq bar2 4)
  (+ foo2 bar2)
  )

(add1)
(add2)

;; now if I try evaluating the following 
foo1 ;; will give error (symbols value as variable is void)
bar1 ;; ditto

foo2 ;; will print 1 
bar2 ;; will print 4

Just to be sure, I would like to know if let is the only way of creating local variables in Elisp code.

Edit: Hmm this seems to be the behavior with Common Lisp too, after running it past my clisp compiler i.e. foo2 and bar2 continue to persist outside the scope of add2

1
  • See Elisp Local Variables. You can find this by: C-h i, choose Elisp manual, i local variables. – Drew Nov 23 '18 at 3:03
2

At a low level the following create local variable bindings:

  • let and let*
  • Function calls
  • Macro calls
  • condition-case

-- C-hig (elisp)Local Variables

However there is also no shortage of other syntax which will expand into code which uses those facilities, and there is not a fixed set of such things to list (any library might provide and use a macro which let-binds some of its arguments, for instance).


Tangentially, you're going to want to understand the difference between dynamic scope (the default scoping rule in elisp), and lexical scope (which is enabled on a per-library basis).

See C-hig (elisp)Variable Scoping

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.