假设我们有一个 Local 类:
class Local {
static inline public var logLevel:Int = 3;
}
以及一些功能:
Tool.debug(s:String) // compiled if logLevel >= 0
Tool.moreinfo(s:String)// compiled if logLevel >= 1
Tool.info(s:String) // compiled if logLevel >= 2
Tool.trace(s:String) // compiled if logLevel >= 3
Tool.warn(s:String) // compiled if logLevel >= 4
Tool.err(s:String) // compiled if logLevel >= 5
我们可以在代码中使用 -D 和一些 #if 来实现这一点。
然而,这意味着始终修改 hxml 文件。即使它只是针对一个值,这对我来说并不理想,因为我的所有配置都位于我的 Local 类中。
如果我们使用简单的 if () 测试该值,则即使从未使用过所有 if 和字符串,代码也会变得更大(因为 logLevel 意味着“常量”)。
是否可以使用宏来解决这两个问题?
Edit:
如果用例这么简单,@stroncium 的答案会容易得多:将所有内容都内联,编译器将进行优化,不需要宏。看http://try.haxe.org/#C44Ec http://try.haxe.org/#C44Ec,看看编译后的JS。
假设Local
是一个普通的类(你手工编写它,你不使用宏或其他任何东西构建它),然后你可以访问Local.logLevel
在宏调用中。
像这样的一些代码可以工作
class Tool {
public static macro function debug( s:ExprOf<String> ):Expr {
if ( Local.logLevel>=0 ) {
// Insert a trace statement into our code.
// You could insert any other kind of statement or { block; of; statements; } also.
return macro trace( $s );
}
else {
// You need to return an expression of some kind.
// This is the equivalent of writing the line "null;" - it does nothing whatsoever.
return macro null;
}
}
}
或者同样的事情,写得更简洁一点,适用于您的所有功能:
class Tool {
public static macro function debug( s:ExprOf<String> ):Expr {
return
if ( Local.logLevel>=0 ) macro trace( "debug: " + $s );
else return macro null;
}
public static macro function moreInfo( s:ExprOf<String> ):Expr {
return
if ( Local.logLevel>=1 ) macro trace( "moreInfo: " + $s );
else return macro null;
}
public static macro function info( s:ExprOf<String> ):Expr {
return
if ( Local.logLevel>=2 ) macro trace( "info: " + $s );
else return macro null;
}
public static macro function trace( s:ExprOf<String> ):Expr {
return
if ( Local.logLevel>=3 ) macro trace( "trace: " + $s );
else return macro null;
}
public static macro function warn( s:ExprOf<String> ):Expr {
return
if ( Local.logLevel>=4 ) macro trace( "warn: " + $s );
else return macro null;
}
public static macro function err( s:ExprOf<String> ):Expr {
return
if ( Local.logLevel>=5 ) macro trace( "err: " + $s );
else return macro null;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)