Does lua support "*" in string formatting?

I was trying to do

-- Lua code
("%*F"):format(unimportant_variable, num)

, but the code checker keeps warning me that there was an argument count mismatch. I tried the same thing in a separate online lua compiler, and the same result come up. I tried the equivalent code in C++ (the language whose string formatting was inherited into lua) and it worked perfectly fine.

// C++ code
#include <iostream>

int main() {
    int unimportant_var = 2;
    double num = 4;
    printf("%0*f", unimportant_var, num);

    return 0;
}

Am I doomed to not be able to use the star width/precision modifier? If so, can anyone provide a workaround for this?

It’s planned:

Well, that’s bloody crummy innit?

Anyways, any possible workarounds perhaps?

None that I know of, sorry. I’m sure that someone else who knows will contribute

If you’re talking about decimal precision, lua has a way to do this directly involving the format string.
The wildcard, %* doesn’t have anything to do with this, at least from the looks of it.

-- Decimal precision.
local precision = 2
local number = 4

print( string.format( string.format( "%%.%if", precision ), number ) )
-- "4.00"

However, if you are talking about zero padding (like you are with the C++ code), you can add 0 as a flag instead.

local zeroPadding = 10
local number = 5

print( string.format( string.format( "%%0%if", zeroPadding ), number ) )
-- Zero Padding takes the decimals and the decimal point into consideration.
-- "005.000000"

If you want to use both, you can just use them sequentially. It doesn’t matter in what order.

local precision = 1
local zeroPadding = 7
local number = 4

print( string.format( string.format( "%%0%i.%if", zeroPadding, precision ), number ) )
-- "00004.0"

There is an article linked below if you need to learn all of the other format flags, or lua formatting in general.

Seems a bit complicated, but sure. Thanks!

1 Like

Yeah, it took me a while to wrap my head around it too, I can lay out a few ground rules.

  1. Flags are put in between the % and the class identifier (f in this circumstance)
  2. Zero padding’s flag is 0. The bolded number is the flag, the italicized number is the specification.
    → "%020f
  3. Precision’s flag is .
    → "%.15f

The same rules go for the rest of the flags. The parameters of each flag can be left empty to have the default value.

Hope this helps.