本文主要是介绍ELisp编程七:创建函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
defun原型
https://www.gnu.org/software/emacs/manual/html_node/eintr/defun.html 里面介绍的defun并不全,可能文档过于老旧了吧。
http://www.gnu.org/software/emacs/manual/html_node/elisp/Defining-Functions.html 要全点,和emacs c-h f显示的差不多
下面是Emacs c-h f显示的defun macro的帮助文档
defun is a Lisp macro.(defun NAME ARGLIST &optional DOCSTRING DECL &rest BODY)Define NAME as a function.
The definition is (lambda ARGLIST [DOCSTRING] BODY...).
See also the function `interactive'.
DECL is a declaration, optional, of the form (declare DECLS...) where
DECLS is a list of elements of the form (PROP . VALUES). These are
interpreted according to `defun-declarations-alist'.
The return value is undefined.[forward]
参数解释
NAME 是函数名称
ARGLIST是函数接受的参数
DOCSTRING 是一个字符串,描述函数的功能,emacs帮助系统会使用它,建议每个函数作者都尽可能写这段描述
DECL是一个宏,用来对函数添加元数据,比如描述该函数要被废除
&rest 可以是interactive,有了它,可以直接在M-x中调用函数
BODY是函数体
简单函数例子
用Emacs创建一个test.el文件。编写如下代码:
(defun add2 (x)(+ 2 x))(add2 8)
第一段是定义了一个函数add2,传递任意数值x,都会加上2后返回,在这个函数的最后的括号后面运行C-x C-e,创建该函数。
然后在到第二段调用代码最后面执行C-x C-e
在Mini-buffer可以看到和为10.
复杂一点的例子
(defun sql-connect-preset (name)"Connect to a predefined SQL connection listed in `sql-connection-alist'"(eval `(let ,(cdr (assoc name sql-connection-alist))(flet ((sql-get-login (&rest what)))(sql-product-interactive sql-product)))))
sql-connect-preset是函数名
interactive
(defun eval-buffer2 ()(interactive)(eval-buffer nil (get-buffer-create "output")))
(interactive)是可以接受参数的,以后再细说。
(let ((variable value)(variable value)...)body...)
下面是一个例子:
(let ((zebra 'stripes)(tiger 'fierce))(message "One kind of animal has %s and another is %s."zebra tiger))
这篇关于ELisp编程七:创建函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!