Using Symbol within function (unexpected behaviour)


I am currently running some simulations and would like to serialize some parameters for the model.
Using symbols I thought I could get away with a concise way of writing it :

c, d = 1, 2                                                                                                                                                                                                       
serialize(open("","w"),Dict(string(x)=>eval(x) for x=[:c,:d]))   

But ran into an unexpected behaviour when running the same code inside a function

using Serialization                                                                                                                                                                                         
function test()                                                                                                                                                                                             
    a ,b = 1                                                                                                                                                                                                                                                                                                                                                                      
    serialize(open("","w"),Dict(string(x)=>eval(x) for x=[:a,:b]))  # ERROR: LoadError: UndefVarError: a not defined                                                                                                                  
 test()  # fails a is undefined                                                                                                                                                                                                     

This seems like a trivial issue but I couldn’t find any help within the documentation…

Thanks in advance for your help!

eval() always operates in global scope. Check out the help text:

help?> eval


  Evaluate an expression in the global scope of the containing module. ...

Since eval() operates in global scope, it does not have access to the values of your local variables.

Since Julia 1.1, though, we have the Base.@locals() macro, which gives you a dictionary mapping local variable names to their local values. Your use case might be a good fit for that:

julia> function foo()
         a = 1
foo (generic function with 1 method)

julia> foo()

Great! I completely missed out that eval was operating on the global scope. Thanks for your help!