Using eval()
inside a macro is almost never necessary, and it’s almost always a signal that something has gone wrong. In this case, there’s no need for eval
at all.
Rather than tackling the full version of your code, here’s a simple example of saving a single variable. First, I defined a stub h5write
function so I don’t actually have to generate hdf files for testing:
julia> function h5write(filename, data, label)
println("saving: $data with label $label in file $filename")
end
h5write (generic function with 1 method)
Then I built a macro to call that function. Note the use of esc(param)
to get the un-escaped variable in the expanded code, and the use of QuoteNode
to turn a variable into a symbol giving the name of that variable:
julia> macro saving(name, param)
quote
h5write(string($name, ".h5"), $(esc(param)), string($(QuoteNode(param))))
end
end
@saving (macro with 1 method)
We can verify that this works at local scope:
julia> let
local_var = [1, 2, 3]
@saving "test" local_var
end
saving: [1, 2, 3] with label local_var in file test.h5
and global scope:
julia> global_var = [1, 2]
2-element Array{Int64,1}:
1
2
julia> @saving "test" global_var
saving: [1, 2] with label global_var in file test.h5