21

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)
oneself
  • 38,641
  • 34
  • 96
  • 120

3 Answers3

34

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.

Miserable Variable
  • 28,432
  • 15
  • 72
  • 133
Timo Geusch
  • 24,095
  • 5
  • 52
  • 70
  • 2
    Yes, you definitely want to avoid trying to use the symbols `t` and `nil` as names for anything. (Except, of course, for themselves -- evaluating them yields the same symbol back.) – SamB Mar 04 '11 at 23:15
  • The `func-caller` function is redundant in this scenario, of course, unless you needed it to evaluate some additional code upon every such function call. – phils Jun 21 '12 at 22:55
6

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.

outis
  • 75,655
  • 22
  • 151
  • 221
Jouni K. Seppänen
  • 43,139
  • 5
  • 71
  • 100
0

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