Search code examples
crystal-lang

Sharing variables between different macros


How to access vars in macro that are set in another macro e.g.

macro foo(arg)
 {% SHARED_VAR = arg%}
 p {{arg}}
end

macro baz

 p {{ SHARED_VAR }}

end

foo("foo")
baz #=> prints "foo"

Solution

  • Well, this is just not a feature of the language, and probably for good reasons.

    Some alternatives:
    Use a constant instead, but you cannot do compile-time things with it:

    macro foo(arg)
      SHARED_VAR = {{arg}}
    end
    
    macro baz
      p SHARED_VAR
    end
    
    foo("foo")
    baz #=> prints "foo"
    

    Or simply call the other macro with the additional information:

    macro foo(arg)
      {% shared_var = arg %}
      baz({{shared_var}})
      p {{arg}}
    end
    
    macro baz(arg)
      p {{arg}}
    end
    
    foo("foo") #=> prints "foo"