Emacs 口齿不清。一个函数无法访问另一个函数中的变量

Emacs lisp. One function to has no access to variables in another function

emacs lisp 中的代码:

 </p>

<p>(defun test-sub-fun-var()
  (message "SUB test-sub-fun-var: my-local-var: %s" my-local-var)
  )</p>

<p>(defun test-main()
  (message "\nSTART test-main")
  (let
      (
       (my-local-var)
       )
    (setq my-local-var "MY LOCAL VARIABLE VALUE")
    (message "MAIN my-local-var: %s" my-local-var)
    (test-sub-fun-var)
    )
  (message "FINISH test-main")
  )</p>

<p>(test-main)
</pre>

当运行函数"test-main"时,我们有结果:

开始测试主

主要 my-local-var:我的局部变量值

SUB test-sub-fun-var: my-local-var: 我的本地变量值

完成测试主

如您所见,函数 "test-sub-fun-var" 可以访问函数 "test-main" 中声明的变量“my-local-var”。但是我需要函数 "test-sub-fun-var" 才能访问变量“my-local-var”。我该怎么做?谢谢

您没有说明您使用的是哪个版本的 Emacs。在 24.1 之前并没有真正的方法来做你想做的事,你只需要小心。但是,引用最新版本的信息手册(26.0.50.1):

11.9.3 Lexical Binding

Lexical binding was introduced to Emacs, as an optional feature, in version 24.1. [...] A lexically-bound variable has “lexical scope”, meaning that any reference to the variable must be located textually within the binding construct.

您使用文件局部变量 lexical-binding 在每个文件的基础上启用词法绑定。所以,

;; -*- lexical-binding:t -*-

(defun test-sub-fun-var()
  (message "SUB test-sub-fun-var: my-local-var: %s" my-local-var))
(defun test-main()
   (message "\nSTART test-main")
   (let ((my-local-var))
       (setq my-local-var "MY LOCAL VARIABLE VALUE")
       (message "MAIN my-local-var: %s" my-local-var)
       (test-sub-fun-var))
   (message "FINISH test-main"))

(test-main)

现在你的输出是:

START test-main
MAIN my-local-var: MY LOCAL VARIABLE VALUE
test-sub-fun-var: Symbol’s value as variable is void: my-local-var