How do I do closures in Emacs Lisp?

后端 未结 8 1891
感动是毒
感动是毒 2020-12-01 03:12

I\'m trying to create a function on the fly that would return one constant value.

In JavaScript and other modern imperative languages I would use closures:



        
8条回答
  •  渐次进展
    2020-12-01 03:26

    I am not firm in Emacs Lisp, but as far as I know, a big difference from Common Lisp is that it uses dynamic scoping throughout. The Emacs Lisp Manual states that Emacs Lisp doesn't have closures.

    I'll try to apply my theoretical knowledge of dynamic scoping.

    If you have a function id which just returns the value of my-id:

    (defun id ()
      my-id)
    

    and you use it in some other function:

    (defun some-other-place ()
      (id))
    

    and somewhere on the way to the call of id you bind my-id through e.g. a let:

    (defun even-elsewhere ()
      (let ((my-id 5))
        (some-other-place)))
    

    this should give back 5.

    I know that dynamic scoping is a strange beast when you are used to lexical scoping, but perhaps you can use this to implement your desired behaviour.

提交回复
热议问题