摆脱“对自由变量的引用"字节编译警告 [英] Get rid of "reference to free variable" byte-compilation warnings
问题描述
我正在编写一个 emacs 主模式,它使用缓冲区局部变量来存储一些状态:
I'm writing an emacs major mode, which uses buffer-local variables to store some state:
(defun foo-mode ()
"My nice major mode"
(interactive)
(kill-all-local-variables)
(setq mode-name "foo")
(setq major-mode 'foo-mode)
(set (make-local-variable 'foo-state) "bar"))
(defun foo-change-state ()
(setq foo-state "baz"))
这很好用,并且具有在任何不使用我的主要模式的缓冲区中的属性,foo-state
变量不受约束(在我看来这是一件好事,因为它避免了混乱符号表).
This works very well and has the property that in any buffer not using my major mode, the foo-state
variable is not bound (which is a good thing in my opinion, since it avoids cluttering the symbols table).
然而,对这样一段代码进行字节编译会产生以下警告:
However, byte-compiling such a piece of code produces the following warning:
Warning: assignment to free variable `foo-state'
使用 defvar
消除了警告,但有一个副作用,即 foo-state
现在到处都是绑定的,这在我看来是不可取的.
Using defvar
gets rid of the warning, but has the side-effect that foo-state
is now bound everywhere, which is undesirable in my opinion.
有没有办法消除警告,同时仍然没有在每个缓冲区中绑定特定于模式的变量?或者我认为这些变量不应该被全局声明是我错了?
Is there a way to get rid of the warnings while still not binding the mode-specific variables in every buffer? Or am I mistaken when I think these variables should not be declared globally?
推荐答案
做你想做的事情的官方方法是 (defvar foo-state)
.注意没有第二个参数.另请注意,此类声明仅适用于找到它的文件(或找到它的范围,如果它在函数内使用).
The official way to do what you want is (defvar foo-state)
. Note the absence of a second argument. Note also that such a declaration only applies to the file where it is found (or to the scope in which it is found, if it's used inside a function).
这篇关于摆脱“对自由变量的引用"字节编译警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!