The Crystal Programming Language Forum

Constants as globals in the macro namespace. Any better way?

Currently I am using a constant as a global in the macro namespace, as shown below. I don’t actually need this constant in the compiled program. Is there a better way to do this?

private Strings = {} of String => Tuple(String, Array(String)|Nil, Array(Tuple(String, Int32))
...
{% if (t = Strings[name]) == nil %}
     {% Strings[name] = { native, exp, [{ original.filename, original.line_number }] } %}
{% else %}
     {% t.last.push({ original.filename, original.line_number }) %}
{% end %}=
...
# After I sort and emit the data:
{% Strings.clear %}

Use Nil as the key type and value type

Works, and very interesting insight into the separate worlds of data structure literals and their compiled successors.

It’s a bit of a hack. It works because constants are not analyzed unless you use them outside of macros.