So, I have a macro that works fine in the REPL, but doesn’t work when called on a script and I don’t know why. The macro simply creates a struct based on information stored in a NamedTuple. There is a regular function that reads the NamedTuple and produces a schema that is a String, and that string is passed to the macro, so that it can create the struct. Later on, that struct is going to be instantiated many times during the course of the program. My idea was to make all that work during compile time because this is a simulation library, so when the user inputed the NamedTuple, the library would compile itself to produce the correct struct and then proceed to run the simulation. I feel I have misunderstood something very deeply, because once the schema string is built it can be called from other macros such as @show, but not from my macro. It raises an error
LoadError: LoadError: UndefVarError: state_signature not defined
But everything works correctly in the REPL.
Any help is appreciated.
export generate_state_signature, @state_factory
macro state_factory(signature::Union{Symbol,String})
schema = eval(signature)
fields = map(x -> Meta.parse(x), split(schema))
return quote
struct State
$(fields...)
timestep::Int64
substep::Int64
function State($(fields...), timestep::Int64, substep::Int64)
new($(fields...), timestep::Int64, substep::Int64)
end
State(;$(fields...), timestep::Int64=1, substep::Int64=1) = State($(fields...), timestep::Int64, substep::Int64)
end
end
end
function generate_state_signature(initial_conditions::NamedTuple)
state_signature = ""
for (variable, value) in pairs(initial_conditions)
type = typeof(value)
state_signature *= "$variable::$type "
end
return state_signature
end
These are the function and macro used on the script.