Evaluation of string with local variable

I have strings in context of symbolic diffferentiation. Therefore I need to evaluate strings which contain local variables.
In the manual to Metaprogramming is this example:

macro zerox()
  return esc(:(x = 0))
end

function foo()
  x = 1
  @zerox
  x  # is zero
end

But why doesn’t work that version?

macro zerox(string)
    return esc(string)
end

function foo()
    x = 1
    b = parse("x = 0")
    @zerox(b)
    x # is now one
end

I really appreciate your help!

No it’s impossible and metaprogramming will never help.

To quote myself in a recent post:

Many people seems to think macro gives you magic power to accomplish things at runtime that are not possible without them. They don’t, they are just a fancy way to save repeated typing.

2 Likes

Okay, that’s important to know! Then I will just ask the other way round:
I have given formulas for nonlinear equations in a txt. document. I rearrange and differentiate them automatically so that I can calculate residuals as well as the Jacobian for the nlsolve() function from the NLsolve package (still in string format). My plan was to parse and evaluate the strings repeatedly in the f!() and j!() function as I have to solve these formulas many times with different parameters depending on the previous solution. How would you approach that?
EDIT: It works more or less with global variables but first it is slow and second it is quite uncomfortable.

You should construct functions from those expressions and pass variables they need to reference as arguments. You have to use eval of it’s variances to construct the function and you have to use invokelatest to call the function after you are done with that.

If you only need to read a text file though, it should be much better to just make that text file a julia file instead and pass the formulas in as functions directly.

1 Like

Thanks a lot! I will try that out…

Hey, I followed your advice and it works perfectly. Thanks!