这是一个简单的问题,但不知何故我无法通过谷歌搜索找到答案:
如果不满足某些条件,如何在任意执行点退出函数。例如(我在这里使用“(退出)”作为替代):
(defun foo ()
(progn (if (/= a1 a2)
(exit) ; if a1!=a2, exit the function somehow
t)
(blahblah...)))
在 elisp 中,您可以使用catch
andthrow
代替 cl 的block
andreturn-from
。
(defun foo ()
(catch 'my-tag
(when (not (/= a1 a2))
(throw 'my-tag "non-local exit value"))
"normal exit value"))
看C-hig (elisp) Nonlocal Exits
RET
在身体周围放一个块并从中返回:
(require 'cl-macs)
(defun foo ()
(block foo
(if (/= a1 a2)
(return-from foo)
reture-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))
函数返回最后评估的表单的值。如果您不在乎价值是什么,那么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"))