Question

Recent versions of Emacs support lexical binding for variables in elisp code. Is it also possible to lexically redefine functions? In other words, does Emacs Lisp have something like lexical-flet?

Was it helpful?

Solution

In Emacs<24.3, you can (require 'cl) and then use labels. In Emacs-24.3 and up, you can also do (require 'cl-lib) and then use either cl-flet or cl-labels.

All of those are "complex macros" that generate code that looks like (let ((fun (lambda (args) (body)))) ... (funcall fun my-args) ...), because the underlying language does not natively support local function definitions.

OTHER TIPS

There is labels but I don't know if that's what you're looking for:

(defun foo ()
  42)

(defun bar ()
  (foo))

(list
 (foo)
 (bar)
 (labels ((foo ()
               12))
   (list (foo)
         (bar)))
 (foo)
 (bar))

It returns (42 42 (12 42) 42 42).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top