2

Is it possible to reference a local variable inside the definition of a function? Here's an example:

I have an alist text-alist consisting of keys and text snippets. I want each text snippet bound to a key in the prefix map my-text-prefix-map. The code below doesn't work, I guess because when the functions in my-text-prefix-map are run, the value of text is unknown. Is there any way to remedy this?

(mapc (lambda (text)
        (define-key my-text-prefix-map (kbd (car text))
          (lambda ()
            (interactive)
            (insert (cdr text)))))
      text-alist)
  • 1
    Do some searching for "closure". You should find many duplicates and approaches. – phils May 17 '16 at 11:11
7

You can use backquotes and commas to build functions dynamically:

`(lambda ()
   (interactive)
   (insert ,(cdr text)))

Or you can also enable lexical-binding to make function closures.

More information on Backquotes can be found in Emacs manual.

  • 3
    Whoever down-voted this, please leave a comment explaining why. Using a backquote is a very common solution to the problem. – phils May 17 '16 at 13:05
  • 3
    I didn't down vote, but I would like to see actual code for the lexbind case which, IMHO, should be the first and preferred suggestion. – YoungFrog May 26 '16 at 9:39
  • 3
    The lexbind solution uses the exact code in the question, just with a -*- lexical-binding:t -*- on the first line (a comment) of the file. – Stefan May 26 '16 at 12:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.