2013-04-27 61 views
10

這是一個簡單的問題,但不知何故,我無法找到谷歌搜索通過一個答案:如何從在任意點的函數退出,在elisp的

你如何在執行的任意點退出功能,如果某些條件不符合。例如(我用「(退出)」作爲替補在這裏):

(defun foo() 
    (progn (if (/= a1 a2) 
      (exit) ; if a1!=a2, exit the function somehow 
      t) 
     (blahblah...))) 

回答

11

在elisp的,你可以使用catchthrowinstead 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 ExitsRET

9

放了一塊周圍的身體,並從它返回:

(require 'cl-macs) 
(defun foo() 
    (block foo 
    (if (/= a1 a2) 
     (return-from foo) 
     reture-value)))) 
+0

我不知道塊。 +1 – RNA 2013-04-29 17:52:10

3

函數返回的最後形式的價值評估。如果你不在意價值是什麼,那麼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")) 
+0

:這不是我的問題。對不起,我以前的例子是誤導性的。我改變了它。 – RNA 2013-04-27 06:00:37

+0

啊,好的。在大多數情況下,您應該能夠構建代碼以避免非本地出口的需求,但是我已經使用標準的elisp方法添加了另一個答案。 – phils 2013-04-27 06:34:09

6

只需使用defun*代替defun(自帶cl封裝)。這個宏已經像Common Lisp的defun(將函數的主體包裝在try-catch塊中並且別名return-fromthrow等等)一樣起作用。

例如:

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