在elisp中,如何将函数放入变量中? [英] In elisp, how do I put a function in a variable?

查看:15
本文介绍了在elisp中,如何将函数放入变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望允许用户在自定义"emacs 后端中选择他们自己的命令(并且通常能够将可执行表单名称存储在变量中),但这不起作用:

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..?

推荐答案

请注意,在 Emacs Lisp 中,符号有一个值单元格和一个函数单元格,它们是不同的.当您评估一个符号时,您会得到它的.当您评估以该符号开头的列表时,您将调用它的函数.这就是为什么您可以拥有同名的变量和函数.

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.

大多数类型的赋值都会设置值(例如 letsetqdefvardefcustom 等...) -- 正如 ryuslash 所示,您可以将函数分配为值并通过 funcall 调用它 -- 但也有一些方法可以直接使用 fset 分配给符号的函数单元格(或 fletdefalias 等)

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)

在你的情况下,我会使用 ryuslash 的答案(除非你需要使用 defcustom 而不是 defvar 如果你希望它通过 customize 可用>).

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

另外,关于我很难用谷歌搜索它";永远记住,Emacs 是自文档化,除其他外,它包含一本带有索引的好手册(嗯,实际上不止一本手册).因此,即使 Google 仍然是您的第一个停靠点,但如果您找不到所需的内容,它也不应该是您的最后一个停靠点.从 elisp 手册的内容页面,您可以导航到函数",然后是调用函数",您几乎会立即被告知 funcall.

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.

这篇关于在elisp中,如何将函数放入变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆