定义函数局部变量
Define variable local to function
我正在(愉快地)学习 Emacs Lisp 编程简介,并且已经解决了第一个 8.7 Searching Exercise。它指出,
Write an interactive function that searches for a string. If the
search finds the string, leave point after it and display a message
that says “Found!”.
我的解决方案是
(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
是您要在此处使用的内容,尽管它 不会 定义 函数的局部变量,但它自己的范围。
您的代码变为:
(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' 评论修改了代码。
我正在(愉快地)学习 Emacs Lisp 编程简介,并且已经解决了第一个 8.7 Searching Exercise。它指出,
Write an interactive function that searches for a string. If the search finds the string, leave point after it and display a message that says “Found!”.
我的解决方案是
(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
是您要在此处使用的内容,尽管它 不会 定义 函数的局部变量,但它自己的范围。
您的代码变为:
(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' 评论修改了代码。