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.
;; 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