How to achieve a print function valid only in debug version?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By moonrise

My purpose is to print something only in debug version but not in release version.

As I known, one way is

if OS.is_debug_build():
   print(XXX)

I try to use such a function:

func debug_print(x):
  if Os.is_debug_build():
     print(x)


debug_print(x) (work)
debug_print(a,b) (failded)
debug_print(a,b,"c") (failded)

However, the function can only handle one argument. How to handle more argmuments like print function?

:bust_in_silhouette: Reply From: Calinou

However, the function can only handle one argument. How to handle more argmuments like print function?

GDScript doesn’t not support variadic function arguments, so you have to use the following approach instead:

func debug_print(arg1 = "", arg2 = "", arg3 = "", arg4 = "", arg5 = "", arg6 = "", arg7 = "", arg8 = ""):
    if OS.is_debug_build():
        print(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)
    

It’s not very elegant, but it works :slight_smile:

The above example supports up to 8 arguments, which is enough in nearly all sitautions you’d use a debug print for.

As you say, it works!
Thanks very much!

moonrise | 2022-09-29 13:54

According to the documentation, the code inside assert is only run in debug mode.

assert(not print(a, b, c, d, e, f))

However, given that print does not return any value, I don’t know if such code will be safe. Apparently, in Godot 3.x, calling assert with “not void” does not generate an error.

Another solution is to pass an array to your function.

func debug_print(x):
  if Os.is_debug_build():
     print(x)
debug_print(x) (work)
debug_print( [ a,b ] ) (work)
debug_print( [ a, b, "c" ] ) (also work)

patwork | 2022-10-23 02:17