如何将函数作为参数传递给elisp?

时间:2008-10-17 18:22:28

标签: emacs 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)

3 个答案:

答案 0 :(得分:31)

首先,我不确定命名您的函数t是否有用,因为't'被用作lisp中的truth value

那就是说,以下代码对我有用:

(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',它会触发实际的函数调用。

答案 1 :(得分:6)

this page末尾的注释表示您可以使用#'而不是'来引用函数,以向字节编译器发出符号始终为函数命名的信号。

答案 2 :(得分:0)

以上答案还不错,但是您可以使用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++))
    )
  )