|
|
Daneel Yaitskov <rtfm.rtfm.rtfm@xxxxxxxxx> writes:
> The snippet of the lisp code:
>
> (defun create-counter (start)
> #'(lambda () (setq start (+ start 1))))
>
>
> It works in the common lisp but not in the emacs lisp.
> The CL creates successfully the counter-functional.
> This snippet works in elisp only when it stands in a environment where
> exist the start variable:
>
> (setq start)
> or
> (let (start) ....
>
> I want to ask is any device exist to do same in the elisp environment.
As others have mentioned, use lexical-let to create a lexical variable
which can then be captured in a closure.
What's going on is that elisp does not have lexical/static scoping, only
dynamic scoping. So as soon as the lambda is returned from the
create-counter function, the `start' variable no longer exists and there
was no such thing as a lexical closure for it to be captured in.
lexical-let fakes lexical variables for elisp, so you can do:
(defun create-counter (start)
(lexical-let ((real-start start))
#'(lambda () (setq real-start (+ real-start 1)))))
HTH,
- Michael
--
mouse, n: A device for pointing at the xterm in which you want to type.
Confused by the strange files? I cryptographically sign my messages.
For more information see <http://www.elehack.net/resources/gpg>.
|
|