Macros 晶体中的Tmp宏变量
如何使用宏中的临时变量在Crystal Lang中构建代码。例如,我有:Macros 晶体中的Tmp宏变量,macros,metaprogramming,crystal-lang,Macros,Metaprogramming,Crystal Lang,如何使用宏中的临时变量在Crystal Lang中构建代码。例如,我有: module Rule macro included {% rules = [] of TypeDeclaration %} macro rule(declaration) raise("Should be TypeDeclaration") unless \{{declaration.is_a?(TypeDeclaration)}} \{
module Rule
macro included
{% rules = [] of TypeDeclaration %}
macro rule(declaration)
raise("Should be TypeDeclaration") unless \{{declaration.is_a?(TypeDeclaration)}}
\{% {{rules}} << declaration %}
end
macro finished
\{% for declaration in rules %}
puts \{{declaration}}
\{% end %}
end
end
end
class StringRule
include Rule
rule min : Int32 = 0
rule max : Int32 = 255
end
模块规则
宏包括
{%rules=[]的类型声明%}
宏规则(声明)
raise(“应该是类型声明”),除非\{declaration.is_a?(类型声明)}
\{%{{rules}}6{%[]宏表达式中的变量的作用域为相应的宏上下文。因此,在包含的宏中定义的变量在宏规则中不可见
但您可以为此使用常量:RULES=[]of
。\u
下划线使数组不类型化,它仅在编译期间使用,不用于实际代码。如果在宏表达式外部引用RULES
,编译器将抱怨
module Rule
macro included
RULES = [] of _
macro rule(declaration)
\{% raise("Should be TypeDeclaration") unless declaration.is_a?(TypeDeclaration) %}
\{% RULES << declaration %}
end
macro finished
\{% for declaration in RULES %}
puts \{{ declaration.stringify }}
\{% end %}
end
end
end
class StringRule
include Rule
rule min : Int32 = 0
rule max : Int32 = 255
end
模块规则
宏包括
规则=[]共_
宏规则(声明)
\{%raise(“应该是类型声明”),除非声明.is_a?(类型声明)%}
\{%谢谢,这对我来说太好了。
module Rule
macro included
RULES = [] of _
macro rule(declaration)
\{% raise("Should be TypeDeclaration") unless declaration.is_a?(TypeDeclaration) %}
\{% RULES << declaration %}
end
macro finished
\{% for declaration in RULES %}
puts \{{ declaration.stringify }}
\{% end %}
end
end
end
class StringRule
include Rule
rule min : Int32 = 0
rule max : Int32 = 255
end