In C ++, you can use predefined macros to implement Conditional compilation, so as to exclude some debugging code from the compilation scope during release. The elegant implementation of an encapsulation is as follows:
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 does not have such a useful macro function, but we also need some debugging statements and hope that they can be quickly blocked or converted to log records during release. I am thinking about writing the following code to meet my needs.
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 end11 end12 13 14 I = 515 16 DebugCode (17 "\ 18 print (12) \ 19 print (I) \ 20 test (I) \ 21" 22)
Notes:
1. You can enter a series of statements to print or store the results to be viewed.
2. Unfortunately, if you want to call a function, the function must be declared first, and if it is global, if it is declared as local, it cannot be found and the loadstring result is used.
3. When releasing a program, you can redefine the function DebugCode to be empty or define DEBUG = false to achieve blocking effect. However, function calls still occur, so it is not ideal.
Note: The C ++ implementation comes from page 207 of code Daquan