In elisp, how do I put a function in a variable?

♀尐吖头ヾ 提交于 2019-11-29 03:22:54

Note that in Emacs Lisp, symbols have a value cell and a function cell, which are distinct. When you evaluate a symbol, you get its value. When you evaluate a list beginning with that symbol, you call its function. This is why you can have a variable and a function with the same name.

Most kinds of assignment will set the value (e.g. let, setq, defvar, defcustom, etc...) -- and as ryuslash shows you can assign a function as a value and call it via funcall -- but there are also ways to assign to a symbol's function cell directly using fset (or flet, defalias, etc)

(fset 'my-function 'dumb-f)
(my-function)

In your case I would use ryuslash's answer (except you need to use defcustom rather than defvar if you want it to be available via customize).

Also, regarding "I'm having a hard time googling for it"; always remember that Emacs is self-documenting, and among other things contains a good manual complete with index (well, more than one manual, in fact). So even if Google remains your first port of call, it shouldn't also be your last if you can't find what you're looking for. From the contents page of the elisp manual you can navigate to "Functions" and then "Calling functions" and you will be told about funcall almost immediately.

To run a function stored in a variable you can use funcall

(defun dumb-f ()
  (message "I'm a function"))

(defvar my-function 'dumb-f)

(funcall my-function)
==> "I'm a function"

@phils' great answer mentions various ways of setting a symbol's function definition, but I also needed a way of getting it.

To get a symbol's value as a function you can use the function symbol-function.

For example:

; remember the old value of 'foo as a function
(set 'foo-backup (symbol-function 'foo))
; change it, to experiment or whatever
(defun foo () whatever)
; revert it back to what it was
(fset 'foo foo-backup)

And indeed the emacs manual was helpful here, in particular:

https://www.gnu.org/software/emacs/manual/html_node/elisp/Symbol-Components.html

https://www.gnu.org/software/emacs/manual/html_node/elisp/Function-Cells.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!