• 打开/关闭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页

  • 相关阅读:
    Codeforces Round #370 (Div. 2) D. Memory and Scores DP
    HDU 5876 Sparse Graph BFS 最短路
    HDU 5875 Function st + 二分
    HDU 5869 Different GCD Subarray Query 离线+树状数组
    2016 ACM/ICPC Asia Regional Dalian Online HDU 5877 Weak Pair treap + dfs序
    detection in video and image
    vs 2012打开vs2013的sln
    dl in image process
    classifier
    mark
  • 原文地址:https://www.cnblogs.com/njucslzh/p/2734313.html
Copyright © 2020-2023  润新知