Macro works in REPL but not in script

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.

Difficult to help with no code, but I am guessing you haven’t thought about macro hygiene.

Thanks, will take a look. I added the code.

I don’t know if that has anything to do with your problem, but the REPL loads, by default, the InteractiveUtils package. If you are using any of its functions, you should add using it in your script as well.

I tried both suggestions, but it didn’t work. Don’t know what else to do…

Provide a minimial (not) working example :slight_smile:

So, for future reference, I fixed it by not using a macro, but by using a function that returns a quote and then eval() it. Macros remain a mystery to me. I could provide more code because the repo is still private, sorry.