Cannot find var's name when I eval an expr

Hi

I wanna use eval an expr but the error says that the var’s name cannot be found.
My function is below :

function cal(jac, rate, Q)
    n_spec = size(jac, 1)

    jac_value = zeros(Float64, n_spec, n_spec)
    for i = 1:n_spec, j=1:n_spec
        expr = Meta.parse(jac[i, j])
        dump(expr)
        Core.eval(Main, expr)
        println(expr.args)
    end

    return jac_value
end

and one of my expr is :(1 * -1 * rate[7] + 1 * -1 * rate[1] * Q[2] ^ 1 + 0)
and dump result is

Expr
  head: Symbol call
  args: Array{Any}((4,))
    1: Symbol +
    2: Expr
      head: Symbol call
      args: Array{Any}((4,))
        1: Symbol *
        2: Int64 1
        3: Int64 -1
        4: Expr
          head: Symbol ref
          args: Array{Any}((2,))
            1: Symbol rate
            2: Int64 7
    3: Expr
      head: Symbol call
      args: Array{Any}((5,))
        1: Symbol *
        2: Int64 1
        3: Int64 -1
        4: Expr
          head: Symbol ref
          args: Array{Any}((2,))
            1: Symbol rate
            2: Int64 1
        5: Expr
          head: Symbol call
          args: Array{Any}((3,))
            1: Symbol ^
            2: Expr
              head: Symbol ref
              args: Array{Any}((2,))
                1: Symbol Q
                2: Int64 2
            3: Int64 1
    4: Int64 0

but it raised an error shows that ERROR: LoadError: UndefVarError: rate not defined
I have tried many ways, but I don’t know how to solve it. Thanks for helping.

eval works at global scope, so it cannot create local variables inside a function, no matter what you do. There’s some related discussion in Unpack named tuples (does anyone know how to do it?) .

Can you pass an anonymous function instead of an expression? That should be more flexible and much more efficient.

2 Likes

Thanks for your reply. May I ask about if I would like to use anonymous function just like you said, is there something like this in Julia?

# something above
rate = zeros(Float64, 10, 10)
f(rate) = rate[10, 1] + 1
# read some new file
# Is there something like this in Julia?
f(rate) = f(rate) + rate[5, 2]
# which can append the function

or can I generate an anonymous function from a string?