'Is there an easier way to write this without putting it in a function?

I do this nearly every line:

if printAll then print("message for debugging") end

Is there a way to syntax sugar this, without putting it in a function?

local function cPrint(text)  --conditional printing
  if printAll then
    print(text)
  end
end

cPrint("message for debugging")

Because that function would have to constantly pass a variable only to find out that it isn't needed. Since printAll is usually false, this kind of misuse of resources is not what I want. This function might get run millions of times per minute, it just feels bad to pass an argument that uses memory only to be discarded.

So is there a way to discard this condition before an argument is passed that's a little nicer to look at? (The main reason being that it's more confusing to read nested if-else structures with those lines in there that start with "if".)



Solution 1:[1]

Does this work for you?

local cPrint
if printAll then
   cPrint=print
else
   cPrint=function()end
end

It saves executing the if, but not the function call.

Here is an alternative, that executes a hidden if, but avoids the function call:

_= printAll and print("message for debugging")

It's not really any more readable than

if printAll then print("message for debugging") end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1