This is a really good use-case for a macro. In fact, JLD2 already has @save which does basically what you are looking for.
If you want to learn how to implement this yourself, I would suggest starting with a simpler macro that takes a set of variable names and produces the dictionary mapping those names as strings to their current values.
This might help you start off:
julia> macro map_name_to_value(variable::Symbol)
quote
$(string(variable)) => $(esc(variable))
end
end
@map_name_to_value (macro with 1 method)
julia> a = 1
1
julia> @map_name_to_value a
"a" => 1
That macro just takes a single variable and produces "variable name" => value. You could extend that to take multiple variables in and then construct a dict out of those name => value pairs.
Finally, you could change your macro to call “matwrite” with that dict.
If you want to have a look at something more advanced that does something similar to what you want, have a look at the @save macro of JLD2 defined in src/loadsave.jl