Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

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

I want to allow the user to choose their own command in the "customize" emacs backend (and generally be able to store an executable form name in a variable) but this does not work :

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

    (defvar my-function "dumb-f")

    (my-function)
    ==> Debugger entered--Lisp error: (invalid-function "dumb-f")

    (setq my-function 'dumb-f)

    (my-function)
    ==> Debugger entered--Lisp error: (invalid-function "dumb-f")

I tried various forms, but still no luck, and I'm having a hard time searching for it, I get kilopages of results about functions and variables, but none about how to put the former in the latter..?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...