oneself
oneself

Reputation: 40321

How do I pass a function as a parameter to in elisp?

I'm trying to pass one method to another in elisp, and then have that method execute it. Here is an example:

(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)

Upvotes: 21

Views: 7947

Answers (3)

Jouni K. Seppänen
Jouni K. Seppänen

Reputation: 44162

The note towards the end of "§13.7 Anonymous Functions" in the Emacs Lisp manual says that you can quote functions with #' instead of ' to signal to the byte compiler that the symbol always names a function.

Upvotes: 6

Víctor Ponce
Víctor Ponce

Reputation: 1

Above answers are okey, but you can do something more interesting with defmacro, wich evaluates functions later for some reason:

(defun n1 ()
  "n1")

(defmacro call-n (n)
  (apply n))

(call-n (n1))

A practical example with a for loop that takes any amount of functions and their arguments:

(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++))
    )
  )

Upvotes: 0

Timo Geusch
Timo Geusch

Reputation: 24351

First, I'm not sure that naming your function t is helping as 't' is used as the truth value in lisp.

That said, the following code works for me:

(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)

Please note the use of 'funcall', which triggers the actual function call.

Upvotes: 35

Related Questions