這是一個簡單的問題,但不知何故,我無法找到谷歌搜索通過一個答案:如何從在任意點的函數退出,在elisp的
你如何在執行的任意點退出功能,如果某些條件不符合。例如(我用「(退出)」作爲替補在這裏):
(defun foo()
(progn (if (/= a1 a2)
(exit) ; if a1!=a2, exit the function somehow
t)
(blahblah...)))
這是一個簡單的問題,但不知何故,我無法找到谷歌搜索通過一個答案:如何從在任意點的函數退出,在elisp的
你如何在執行的任意點退出功能,如果某些條件不符合。例如(我用「(退出)」作爲替補在這裏):
(defun foo()
(progn (if (/= a1 a2)
(exit) ; if a1!=a2, exit the function somehow
t)
(blahblah...)))
在elisp的,你可以使用catch
和throw
instead of cl's block
and return-from
。
(defun foo()
(catch 'my-tag
(when (not (/= a1 a2))
(throw 'my-tag "non-local exit value"))
"normal exit value"))
參見C-H我克(elisp) Nonlocal Exits
RET
放了一塊周圍的身體,並從它返回:
(require 'cl-macs)
(defun foo()
(block foo
(if (/= a1 a2)
(return-from foo)
reture-value))))
函數返回的最後形式的價值評估。如果你不在意價值是什麼,那麼nil
將是一個可能的候選人。在這種情況下,該函數返回if
函數的值。
例如爲:
(defun foo()
(if (/= a1 a2)
nil
"return-value"))
在這個簡單的例子,這些也將是等效的:
(defun foo()
(if (not (/= a1 a2))
"return-value"))
(defun foo()
(when (not (/= a1 a2))
"return-value"))
只需使用defun*
代替defun
(自帶cl
封裝)。這個宏已經像Common Lisp的defun
(將函數的主體包裝在try-catch塊中並且別名return-from
到throw
等等)一樣起作用。
例如:
(require 'cl)
(defun* get-out-early()
"Get out early from this silly example."
(when (not (boundp some-unbound-symbol))
(return-from get-out-early))
;;
;; Get on with the func...
;;
(do-such-and-such with-some-stuff))
我不知道塊。 +1 – RNA 2013-04-29 17:52:10