Equana

Back to Tutorials

Dynamic Code Evaluation

Evaluate Equana code from strings at runtime

Run AllReset

The eval function lets you execute Equana code stored in strings. This enables dynamic code generation, runtime expression building, and flexible scripting patterns.

This tutorial demonstrates how to use eval effectively, including capturing return values and understanding workspace effects.

Basic Usage

Pass a string containing Equana code to eval. The code is parsed and executed in the current workspace:

Code [1]Run
# Simple expression evaluation
result = eval("2 + 3")
println(result)

# Create a variable dynamically
eval("x = 10")
println(x)  # x is now in workspace

Capturing Return Values

When you assign the result of eval to a variable, it captures the value of the last expression evaluated:

Code [2]Run
# eval returns the result of the last expression
a = eval("5 * 5")
println(a)

# Evaluate a function call and capture result
B = eval("zeros(2, 3)")
println(B)

# Evaluate math expression
angle = eval("pi / 4")
result = eval("sin(angle)")
println(result)

Workspace Effects

Variables created or modified inside eval affect the current workspace. This means you can dynamically create variables that persist after the eval call:

Code [3]Run
# Variables created in eval persist in workspace
eval("a = 5")
eval("b = 10")
c = a + b
println(c)  # 15

# Modify existing variables
x = 100
eval("x = x * 2")
println(x)  # Now 200

Building Expressions Dynamically

Use string interpolation to construct code at runtime — useful when the operation depends on runtime data:

Code [4]Run
# Dynamic function selection
x = pi / 4

# Build and evaluate expressions from strings
for name in ["sin", "cos", "tan"] {
  expr = "${name}(${x})"
  result = eval(expr)
  println("${name}(pi/4) = ${result}")
}
Code [5]Run
# Generate a series of assignments
for i in 1:5 {
  eval("v${i} = ${i * i}")
}

# The variables now exist in the workspace
println(v1)  # 1
println(v3)  # 9
println(v5)  # 25

Multi-line Code

Pass multi-line code using string interpolation or newlines:

Code [6]Run
# Multi-line eval with newlines
code = "a = 3\nb = 4\nc = sqrt(a^2 + b^2)"
result = eval(code)
println("Hypotenuse: " + string(result))

Common Use Cases

While direct code is usually preferable, eval is useful for:

  • Dynamic function selection based on runtime conditions
  • Evaluating user-provided expressions from input
  • Building code from configuration or data
  • Interactive scripting and experimentation

Tips

Readability: Direct code is usually easier to read and debug than dynamically constructed strings. Use eval when you genuinely need runtime code generation.

Error handling: If the string contains invalid syntax, eval throws a ParseError. Wrap in try/catch if needed:

Code [7]Run
try {
  eval("this is not valid code +++")
} catch e {
  println("Error: " + e.message)
}

Workbench

Clear
No variables in workbench

Next Steps