【问题标题】:Define variable local to function定义函数局部变量
【发布时间】:2017-08-29 01:40:27
【问题描述】:

我正在(愉快地)完成Emacs Lisp 编程简介并解决了第一个8.7 Searching Exercise。它指出,

编写一个搜索字符串的交互式函数。如果 搜索找到字符串,在它后面留下点并显示一条消息 上面写着“找到了!”。

我的解决办法是

(defun test-search (string)
  "Searches for STRING in document.
Displays message 'Found!' or 'Not found...'"
  (interactive "sEnter search word: ")
  (save-excursion
    (beginning-of-buffer)
    (setq found (search-forward string nil t nil))) 
  (if found
      (progn
        (goto-char found)
        (message "Found!"))
    (message "Not found...")))

如何使found 成为该函数的本地函数?我知道let 语句定义了一个局部变量。但是,如果找到string,我只想移动点。我不清楚如何在本地定义found,但如果找不到string,则不能将点设置为beginning-of-buffer。 let 是否适合这种情况?

【问题讨论】:

  • 您确实应该将let 用于临时范围变量(它们在let 表单的范围内是本地的,但对于 function 来说不是本地的,除非是词法-binding 正在使用中,并且变量没有被标记为动态)。
  • 例如:(let ((found (save-excursion (goto-char (point-min)) (search-forward string nil t nil)))) (if found ...))
  • 或者,您可能会在成功搜索后留下点,但在搜索不成功后恢复原始位置。

标签: emacs let cursor-position


【解决方案1】:

正如某些 cmets 中所述,let 是您要在此处使用的,虽然它不会定义函数的局部变量,而是自己的。

你的代码变成:

(defun test-search (string)
   "Searches for STRING in document.
Displays message 'Found!' or 'Not found...'"
   (interactive "sEnter search word: ")
   (let ((found (save-excursion
                  (goto-char (point-min))
                  (search-forward string nil t nil))))
     (if found
       (progn
         (goto-char found)
         (message "Found!"))
       (message "Not found..."))))

编辑:感谢phils'comment 修改代码。

【讨论】:

  • 注意写elisp的时候应该使用(goto-char (point-min))而不是(beginning-of-buffer)。
  • 谢谢@phils ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多