3

For example,

(lambda () (message "%s" x)))

But I would like x to be evaluated -- the lambda function should always use that value, instead of the current value of x. How should I do it?

Preferably lexical-binding is not required.

5

If you don't want to use lexical binding then you will need to use a sexp that evaluates to a lambda form (a list) where x has been replaced by the value you want (e.g., the value that x has at the time the list is created). Like this:

`(lambda () (message "%s" ,x))
2

If you are using lexical binding (lexical-binding is t), then you can store the current value of x in a closure:

(setq lexical-binding t)
(setq x 42)
(setq f (let ((x x)) (lambda () (message "%s" x))))
(setq x 57)
(funcall f)
==> "42"

If you're not using lexical binding, then, as Drew suggested, you must perform some sexp surgery using backquote:

(setq lexical-binding nil)
(setq x 42)
(setq f `(lambda () (message "%s" ,x)))
(setq x 57)
(funcall f)
==> "42"

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.