打开/关闭debug代码段

在C++中可以通过预定义宏,实现条件编译,从而实现将一些调试代码在发布的时候排除出编译范围。一种封装后的优雅实现如下

 1 #define DEBUG
 2 #if defined( DEBUG )
 3 #define DebugCode( code_fragment) { code_fragment }
 4 #else
 5 #define DebugCode( code_fragment )
 6 #endif
 7 
 8 DebugCode(
 9     statement 1;
10     statement 2;
11     ...
12     statement n;
13 );

Lua并没有如此好用的宏功能,但我们也需要一些调试功能的语句,并希望可以在发布的时候快速地屏蔽他们或者转换为log记录。个人琢磨着写了下面的代码,多少能满足一下需求。

 1 function test(x)
 2     print('x=',x)
 3 end
 4 
 5 local DEBUG = true
 6 
 7 local function DebugCode(...)
 8     if DEBUG == true then
 9         loadstring(...)()
10     end
11 end
12 
13 
14 i = 5
15 
16 DebugCode(
17 "\
18 print(12) \
19 print(i)\
20 test(i)\
21 "
22 )

说明几点:

1.可以输入一系列语句,打印或转存要查看的结果。

2.不幸的是,如果要调用函数,则函数要先声明,而且要是全局的,如果声明为local的,则找不到,使用loadstring的结果。

3.发布程序的时候可以重定义函数DebugCode为空或者定义DEBUG = false来实现屏蔽效果,但这里仍有函数调用发生,所以感觉不是特别理想。

 

注:C++实现出自《代码大全》207页

posted on 2012-10-22 17:54  小交响曲  阅读(978)  评论(0编辑  收藏  举报

导航