Open/close debug code snippet

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.