Define variable local to function

為{幸葍}努か 提交于 2019-12-12 13:24:34

问题


I am working (joyfully) working through the Introduction to Emacs Lisp Programming and have solved the first 8.7 Searching Exercise. It states,

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!”.

My solution is

(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...")))

How do I make found be local to the function? I know that a let statement defines a local variable. However, I only want to move point if the string is found. It's not clear to me how to define found locally, yet not have the point be set to the beginning-of-buffer if the string isn't found. Is let the proper command for this situation?


回答1:


As stated in some comments, let is what you want to use here, although it will not define a variable local to the function, but a scope of its own.

Your code becomes:

(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..."))))

Edit: code modified thanks to phils'comment.



来源:https://stackoverflow.com/questions/43197337/define-variable-local-to-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!