Home > Mobile >  Lua and conditional "compilation" : need clarification
Lua and conditional "compilation" : need clarification

Time:10-29

I understood that there is no preprocessor in LUA, so nothing like #define and so on. But I'd like to have "debug" options. For example, I'd like an optional console debug like :

if do_debug then
  function msg(s) 
    print(s) 
  end
else
  function msg(s) 
  end
end

msg(string.format(".............",v1,v2,......))

It works, but I wonder what is the CPU cost in "no debug" mode. The fact is that I call a lot of these msg() function with large strings, sometimes built and formated with a lot of variables. So I would like to avoid extra work. But I suppose that LUA is not clever enough to see that my function is empty, and that there's no need to build its parameter...

So is there a turnaround to avoid these extra costs in LUA ?

NB : you may say that the CPU cost is negligible, but I'm using this for a realtime audio process and CPU does matter in this case.

CodePudding user response:

You can't avoid the creation and unwinding of the stack frame for the msg function. But what you can improve, at least in the snippet shown, is moving the string.format call into msg:

if do_debug then
  function msg(...)
    print(string.format(...))
  end
else
  function msg() end
end

msg(".............",v1,v2,......)

Another approach, trading readability for performance, would be to always do the if do_debug right where you want to print the debug message. A conditional check is much faster than a function call.


But the only way to truly avoid the function call that I know of would be to compile your own version of the Lua interpreter, with a (at least rudimentary) preprocessor added to the parser.

  • Related