如何克服缺少本地变量的emacs lisp关闭 [英] How to overcome the lack of local variable for emacs lisp closure
问题描述
我正在从参考手册学习Emacs Lisp,来自 LISP 的常见Lisp。
从Common Lisp书
>> (setf power-of-two
(let((previous-power-of-two 1))
#'(lambda()
(setf previous-power-of-two
(* previous-power-of-two 2)))))
>> (funcall power-of-two)
2
>> (funcall power-of-two)
4
>> (funcall power-of-two)
8
该功能在Emacs中不起作用Lisp因为它的动态绑定行为。
我想知道是否可以在Emacs Lisp中实现相同的功能,而不引入全局变量?
$ b $现在,Emacs 24已经正式发布,它支持词法绑定。不使用 lexical-let
,当缓冲区局部变量 lexical-binding
不为零时。另请参阅 M-:(info(elisp)using lexical binding)
和pokita的答案。 您可以使用 lexical-let /html_mono/cl.htmlrel =nofollow> Common Lisp Extensions (CL package):
elisp的> (require'cl)
cl
elisp> (setf power-of-two
(lexical-let((previous-power-of-two 1))
#'(lambda()
(setf previous-power-of-two
(* previous-power-of-two 2)))))
(lambda
(& rest --cl-rest--)
(apply
(lambda
(G175638)
(设置G175638
(*
(符号值G175638)
2)))
'--previous-力量二 - - 休息 - ))
elisp> (funcall power-of-two)
2
elisp> (funcall power-of-two)
4
elisp> (funcall power-of-two)
8
我也听说过一个lexbind GNU Emacs的分支。
I'm now studying Emacs Lisp from the reference manual and Common Lisp from a LISP Book.
from the Common Lisp book
>> (setf power-of-two
(let ((previous-power-of-two 1))
#'(lambda ()
(setf previous-power-of-two
(* previous-power-of-two 2)))))
>> (funcall power-of-two)
2
>> (funcall power-of-two)
4
>> (funcall power-of-two)
8
The function won't work in Emacs Lisp because of its dynamic binding behavior.
I wonder if it is possible to implement the same function in Emacs Lisp without introducing a global variable ?
Update:
By now, Emacs 24 has been officially released, and it supports lexical binding without using lexical-let
, when the buffer-local variable lexical-binding
is non-nil. See also M-: (info "(elisp) using lexical binding")
and pokita's answer.
You can use lexical-let
from the Common Lisp Extensions (the "CL package"):
elisp> (require 'cl)
cl
elisp> (setf power-of-two
(lexical-let ((previous-power-of-two 1))
#'(lambda ()
(setf previous-power-of-two
(* previous-power-of-two 2)))))
(lambda
(&rest --cl-rest--)
(apply
(lambda
(G175638)
(set G175638
(*
(symbol-value G175638)
2)))
'--previous-power-of-two-- --cl-rest--))
elisp> (funcall power-of-two)
2
elisp> (funcall power-of-two)
4
elisp> (funcall power-of-two)
8
I've also heard about a lexbind branch of GNU Emacs.
这篇关于如何克服缺少本地变量的emacs lisp关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!