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.

Drew
  • 75,699
  • 9
  • 109
  • 225
xuhdev
  • 1,839
  • 13
  • 26

2 Answers2

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))
Drew
  • 75,699
  • 9
  • 109
  • 225
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"
jch
  • 5,680
  • 22
  • 39