I'm using a closure to keep track of some stuff to do with state; I want to be able to ‘include’ a function into that closure, so it can access the state. The only way this is possible is by creating that function inside the closure.
My idea is to have a function include
, itself created inside that lexical
environment, which takes a quoted lambda form, and then returns the actual
function (which will have been created inside the closure).
Given that lambda
is actually a macro which expands to another macro call
(function (lambda ...))
my best attempt has been
;;; -*- lexical-binding: t; -*-
(let ((x 0)) ;; to represent some state variable
(defun include (quoted-lambda)
(eval
(macroexpand quoted-lambda)
t))) ;; last `t' is to eval with lexical binding
and then
(defalias 'incx (include '(lambda ()
(incf x))))
(incx) ;; should get 1
but this just results in (void-variable x)
!
How can this be fixed?
lexical-binding
at the top of the containing file? That's needed, to get properlexical-binding
behavior.-*- lexical-binding: t; -*-
in; doeseval-buffer
take note of it? (That's what I was using to run the thing.) EDIT: yup,eval-buffer
is affected by that header, so that doesn't seem to be the problem.eval-buffer
does not look at the header: it'sfind-file
(and its ilks) which does. Along the same lines thelambda
macro does not expands to another macro callfunction
is not a macro but a special form).function
misunderstanding in question. The point about the header was just to make sure that lexical binding was on, but thank you for the correction.