[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: How do I remove "reference to free variable" warnings on buffer-loca
From: |
Pascal J. Bourguignon |
Subject: |
Re: How do I remove "reference to free variable" warnings on buffer-local variables? |
Date: |
Mon, 09 Nov 2009 18:40:42 +0100 |
User-agent: |
Gnus/5.1008 (Gnus v5.10.8) Emacs/22.3 (darwin) |
rocky <rocky@gnu.org> writes:
> I have code that uses buffer local variables. I don't want to declare
> this variable global. So how can I remove messages of the form
> "reference to free variable `...' " when I byte compile a file?
A free variable is a variable that is used inside a function that is
not defined locally. It must be considered a global variable.
As indicated in the other answers, if no such global variable is
declared, then you get this warning.
The point is that most often, you don't want a global variable
(otherwise you would have used defvar to define it), but you want a
local variable, and you used setq or setf instead of let.
Use let (or let*) to define local variables. Instead of writing:
(defun equa2 (a b c)
(setq delta (- (* b b) (* 4 a c)))
(cond ((< delta 0) '())
((= delta 0) (list (/ (- b) 2 a)))
(t (list (/ (+ (- b) (sqrt delta)) 2 a)
(/ (- (- b) (sqrt delta)) 2 a)))))
write:
(defun equa2 (a b c)
(let ((delta (- (* b b) (* 4 a c))))
(cond ((< delta 0) '())
((= delta 0) (list (/ (- b) 2 a)))
(t (list (/ (+ (- b) (sqrt delta)) 2 a)
(/ (- (- b) (sqrt delta)) 2 a))))))
In general, try to avoid setq or setf, and rather use the functional
programming style.
--
__Pascal Bourguignon__