Warning: This is the manual of the legacy Guile 2.2 series. You may want to read the manual of the current stable series instead.

Next: , Previous: , Up: Read/Load/Eval/Compile   [Contents][Index]


6.18.10 Local Evaluation

Guile includes a facility to capture a lexical environment, and later evaluate a new expression within that environment. This code is implemented in a module.

(use-modules (ice-9 local-eval))
syntax: the-environment

Captures and returns a lexical environment for use with local-eval or local-compile.

Scheme Procedure: local-eval exp env
C Function: scm_local_eval (exp, env)
Scheme Procedure: local-compile exp env [opts=()]

Evaluate or compile the expression exp in the lexical environment env.

Here is a simple example, illustrating that it is the variable that gets captured, not just its value at one point in time.

(define e (let ((x 100)) (the-environment)))
(define fetch-x (local-eval '(lambda () x) e))
(fetch-x)
⇒ 100
(local-eval '(set! x 42) e)
(fetch-x)
⇒ 42

While exp is evaluated within the lexical environment of (the-environment), it has the dynamic environment of the call to local-eval.

local-eval and local-compile can only evaluate expressions, not definitions.

(local-eval '(define foo 42)
            (let ((x 100)) (the-environment)))
⇒ syntax error: definition in expression context

Note that the current implementation of (the-environment) only captures “normal” lexical bindings, and pattern variables bound by syntax-case. It does not currently capture local syntax transformers bound by let-syntax, letrec-syntax or non-top-level define-syntax forms. Any attempt to reference such captured syntactic keywords via local-eval or local-compile produces an error.