【问题标题】:How do I pass a function as a parameter to in elisp?如何将函数作为参数传递给 elisp?
【发布时间】:2010-09-17 19:34:30
【问题描述】:

我试图在 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)

【问题讨论】:

    标签: emacs elisp


    【解决方案1】:

    首先,我不确定将函数命名为 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”的使用,它会触发实际的函数调用。

    【讨论】:

    • 是的,您绝对希望避免尝试使用符号 t 和 nil 作为任何名称。 (当然,除了它们自己——评估它们会返回相同的符号。)
    • func-caller 函数在这种情况下当然是多余的,除非您需要它在每次此类函数调用时评估一些额外的代码。
    【解决方案2】:

    Emacs Lisp manual 中“§13.7 Anonymous Functions”末尾的注释说,您可以使用 #' 而不是 ' 来引用函数,以向字节编译器发出信号,该符号始终命名函数。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-27
        • 2018-06-30
        • 2020-12-18
        • 1970-01-01
        • 1970-01-01
        • 2021-04-13
        • 1970-01-01
        相关资源
        最近更新 更多