[英]How do I pass a function as a parameter to in elisp?
我试图在 elisp 中将一个方法传递给另一个方法,然后让该方法执行它。 下面是一个例子:
(defun t1 ()
"t1")
(defun t2 ()
"t1")
(defun call-t (t)
; how do I execute "t"?
(t))
; How do I pass in method reference?
(call-t 't1)
首先,我不确定将函数命名为t
是否有帮助,因为 't' 被用作 lisp 中的真值。
也就是说,以下代码对我有用:
(defun test-func-1 () "test-func-1"
(interactive "*")
(insert-string "testing callers"))
(defun func-caller (callee)
"Execute callee"
(funcall callee))
(func-caller 'test-func-1)
请注意“funcall”的使用,它会触发实际的函数调用。
Emacs Lisp 手册中“ §13.7 匿名函数”末尾的注释说,您可以用#'
而不是'
来引用函数,以向字节编译器发出信号,该符号总是命名一个函数。
上面的答案没问题,但是您可以使用 defmacro 做一些更有趣的事情,稍后出于某种原因对函数进行评估:
(defun n1 ()
"n1")
(defmacro call-n (n)
(apply n))
(call-n (n1))
一个带有 for 循环的实际示例,它接受任意数量的函数及其参数:
(defmacro for (i &optional i++ &rest body)
"c-like for-loop"
(unless (numberp i++) (push i++ body) (setq i++ 1))
(while (/= i 0)
(let ((args 0))
(while (nth args body)
(apply (car (nth args body))
(cdr (nth args body)))
(setq args (1+ args))))
(setq i (- i i++))
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.