RNA*_*RNA 10 emacs elisp function exit
这是一个简单的问题,但不知何故,我无法通过谷歌搜索找到答案:
如果不满足某些条件,如何在任意执行点退出函数.例如(我在这里使用"(exit)"代替):
(defun foo ()
(progn (if (/= a1 a2)
(exit) ; if a1!=a2, exit the function somehow
t)
(blahblah...)))
Run Code Online (Sandbox Code Playgroud)
phi*_*ils 12
在elisp中,您可以使用catch而throw 不是cl block和return-from.
(defun foo ()
(catch 'my-tag
(when (not (/= a1 a2))
(throw 'my-tag "non-local exit value"))
"normal exit value"))
Run Code Online (Sandbox Code Playgroud)
看到 C-hig (elisp) Nonlocal Exits RET
在身体周围放一块并从中返回:
(require 'cl-macs)
(defun foo ()
(block foo
(if (/= a1 a2)
(return-from foo)
reture-value))))
Run Code Online (Sandbox Code Playgroud)
小智 8
只需使用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))
Run Code Online (Sandbox Code Playgroud)