【问题标题】:Emacs Lisp nested function - void-variable errorEmacs Lisp 嵌套函数 - 无效变量错误
【发布时间】:2015-10-28 04:29:47
【问题描述】:

我想做一个计时器,像这样:

(defun dumb (y)
  (defun P () (print y))
  (run-with-timer 0 5 'P))

(dumb 5)

然后 Emacs 给我这个错误:

Error running timer `P': (void-variable y)

我想问题是在(defun P () (print y)) 行中,变量y 没有被评估,所以当我运行(dumb 5) 时,函数P 尝试打印y,这是未定义的,而是文字5。但我不知道如何解决它。有什么想法吗?

【问题讨论】:

    标签: elisp emacs24


    【解决方案1】:

    首先,defun 用于在全局范围内定义函数。您只需要使用 lambda 形式构建一个匿名函数。

    其次,y 仅在执行 dumb 时绑定到一个值(动态范围)。向run-with-timer 注册函数是异步的并立即退出。当您的回调被调用时,y 不再绑定。

    您可以使用文件局部变量在当前缓冲区中激活lexical binding

    ;;; -*- lexical-binding: t -*-
    (defun dumb (y)
      (run-with-timer 0 5 (lambda () (print y))))
    

    或者,当lexical-bindingnil 时,您可以“构建”注入当前绑定值y 的lambda 表单:

    (defun dumb (y)
      (run-with-timer 0 5 `(lambda () (print ,y))))
    

    【讨论】:

      【解决方案2】:

      解决这个问题的另一种方法是将额外的参数传递给run-with-timer

      (defun dumb (y)
        (run-with-timer 0 5 'print y))
      

      run-with-timer 在要调用的函数之后接受任意数量的参数,这些参数将在计时器触发时传递。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-31
        • 2012-03-12
        相关资源
        最近更新 更多