Code.eval_string
eval_string, go back to Code module for more information.
Specs
eval_string(List.Chars.t(), binding(), Macro.Env.t() | keyword()) :: {term(), binding()}
Evaluates the contents given by string.
The binding argument is a list of variable bindings.
The opts argument is a keyword list of environment options.
Warning: string can be any Elixir code and will be executed with
the same privileges as the Erlang VM: this means that such code could
compromise the machine (for example by executing system commands).
Don't use eval_string/3 with untrusted input (such as strings coming
from the network).
Options
Options can be:
:file- the file to be considered in the evaluation:line- the line on which the script starts
Additionally, the following scope values can be configured:
:aliases- a list of tuples with the alias and its target:requires- a list of modules required:functions- a list of tuples where the first element is a module and the second a list of imported function names and arity; the list of function names and arity must be sorted:macros- a list of tuples where the first element is a module and the second a list of imported macro names and arity; the list of function names and arity must be sorted
Note that setting any of the values above overrides Elixir's default
values. For example, setting :requires to [] will no longer
automatically require the Kernel module. In the same way setting
:macros will no longer auto-import Kernel macros like Kernel.if/2,
Kernel.SpecialForms.case/2, and so on.
Returns a tuple of the form {value, binding},
where value is the value returned from evaluating string.
If an error occurs while evaluating string an exception will be raised.
binding is a list with all variable bindings
after evaluating string. The binding keys are usually atoms, but they
may be a tuple for variables defined in a different context.
Examples
iex> {result, binding} = Code.eval_string("a + b", [a: 1, b: 2], file: __ENV__.file, line: __ENV__.line)
iex> result
3
iex> Enum.sort(binding)
[a: 1, b: 2]
iex> {result, binding} = Code.eval_string("c = a + b", [a: 1, b: 2], __ENV__)
iex> result
3
iex> Enum.sort(binding)
[a: 1, b: 2, c: 3]
iex> {result, binding} = Code.eval_string("a = a + b", [a: 1, b: 2])
iex> result
3
iex> Enum.sort(binding)
[a: 3, b: 2]For convenience, you can pass __ENV__/0 as the opts argument and
all imports, requires and aliases defined in the current environment
will be automatically carried over:
iex> {result, binding} = Code.eval_string("a + b", [a: 1, b: 2], __ENV__)
iex> result
3
iex> Enum.sort(binding)
[a: 1, b: 2]