scope - Populating a julia dictionary with an array of symbols -
i'm getting stuck on basics of scope in julia expressions. can tell me going wrong inside loop below? inside lopp first expression works , second not, though both work variables global scope.
x = 1 glob_obj = :x eval(:(println($glob_obj))) eval(:(println("$glob_obj"))) # prints # 1 # x objs = [:x] obj = objs eval(:(println($obj))) eval(:(println("$obj"))) end # prints # 1 # error: obj not defined # in anonymous @ no file:3 for context, interested in writing julia function populates dictionary array of symbols in local scope, i.e., function like
x = 1 y = "foo" populate_dict([:x, :y]) # ...resulting in { "x" => 1, "y" => "foo"} importantly, i'd able use in function , have pick variables local scope. more context, easily write json files arbitrary lists of symbols.
the scoping issue running eval evaluates expressions in global scope (the current module, unless specified otherwise). in particular case, deal using
println(obj) instead of eval(:(println("$obj"))); there's no evaluation necessary @ symbol itself!
but if ultimate goal pick values of local variables in function, answer indicated above eval doesn't that. pretty deep design decision allows compiler sorts of optimizations wouldn't able otherwise.
it possible @ local variables aid of debug package, see answer execute string?.
Comments
Post a Comment