Is there a way to specify the position of arguments in a format string for `string.format`?

In C, I can tell printf print the arguments in a different order than the order in which they are passed:

 printf("%2$d %1$d\n", 10, 20); //prints 20 10 

However, if I try to do the same in Lua, I get an error:

 print(string.format("%2$d %1$d\n", 10, 20)) 
 invalid option '%$' to 'format' 

Is there a way to create a Lua format string that causes string.format to write the second argument before the first? I work with internationalization, and changing the format string is easy, but changing the order of the arguments is much more complicated.

I would expect the method I used in C to work with Lua, because according to the manual , string.format should get the same parameters as sprintf . The %2$ directives are not part of ANSI C, or are they Lua guidelines, just forgetting to mention that they are not supported?

+7
lua printf
source share
1 answer

In short, no. %2$ is a POSIX extension, so it is not part of ANSI C or Lua. This was shown earlier on the Lua mailing list and according to lhf , this feature was in versions prior to Lua 5, but was removed with the release of this version. In the same topic, an alternatives wiki page was suggested.

If you really want the style of %2$ , then it’s not too difficult to prepare your own fix.


 local function reorder(fmt, ...) local args, order = {...}, {} fmt = fmt:gsub('%%(%d+)%$', function(i) table.insert(order, args[tonumber(i)]) return '%' end) return string.format(fmt, table.unpack(order)) end print(reorder('%2$d %1$d\n', 10, 20)) 
+8
source share

All Articles