eval
eval([m::Module], expr::Expr)
Evaluate an expression in the given module and return the result. Every Module
(except those defined with baremodule
) has its own 1-argument definition of eval
, which evaluates expressions in that module.
Examples
-
Evaluate an expression in the current module:
julia> x = 5; julia> eval(:(x + 10)) 15
In this example, the expression
x + 10
is evaluated in the current module, resulting in the value15
. -
Evaluate an expression in a specific module:
julia> mod = Module(); julia> eval(mod, :(y = 20)) 20
Here, the expression
y = 20
is evaluated in the modulemod
, and the value20
is returned. - Evaluate a dynamically constructed expression:
julia> a = 2; julia> b = 3; julia> expr = :(a + b); julia> eval(expr) 5
This example demonstrates how to construct an expression using the
:
syntax and evaluate it usingeval
.
Common mistake example:
julia> eval([:x, :y, :z])
ERROR: MethodError: no method matching eval(::Array{Symbol,1})
In this example, an array of symbols [:x, :y, :z]
is passed to eval
instead of an Expr
object. eval
expects an expression, not an array of symbols. To evaluate multiple expressions, you can create a block expression using Expr(:block, ...)
or use a loop to evaluate each symbol individually.
See Also
assert, backtrace, code_llvm, code_lowered, code_native, code_typed, code_warntype, :@which, compilecache, current_module, eval, finalize, finalizer, fullname, function_module, function_name, include_dependency, InterruptException, invoke, isconst, isdefined, isgeneric, methodswith, method_exists, module_name, module_parent, require, subtypes, unsafe_load, workspace, __precompile__,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.