26

This may seem like a stupid question, but what are the symbols used for string replacement in string.format? can someone point me to a simple example of how to use it?

RCIX
  • 38,647
  • 50
  • 150
  • 207

4 Answers4

24

string.format in Lua follows the same patterns as Printf in c:

https://cplusplus.com/reference/cstdio/printf/

There are some exceptions, for those see here:

http://pgl.yoyo.org/luai/i/string.format

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
10

Chapter 20 of PiL describes string.format near the end:

The function string.format is a powerful tool when formatting strings, typically for output. It returns a formatted version of its variable number of arguments following the description given by its first argument, the so-called format string. The format string has rules similar to those of the printf function of standard C: It is composed of regular text and directives, which control where and how each argument must be placed in the formatted string.

The Lua Reference says:

The format string follows the same rules as the printf family of standard C functions. The only differences are that the options/modifiers *, l, L, n, p, and h are not supported and that there is an extra option, q.

The function is implemented by str_format() in strlib.c which itself interprets the format string, but defers to the C library's implementation of sprintf() to actually format each field after determining what type of value is expected (string or number, essentially) to correspond to each field.

RBerteig
  • 41,948
  • 7
  • 88
  • 128
6

There should be "Lua Quick Reference" html file in your hard disk, if you used an installation package.
(for example: ../Lua/5.1/docs/luarefv51.html)

There you'll find, among other things,

string.format (s [, args ])

  • Formatting directives
  • Formatting field types
  • Formatting flags
  • Formatting examples
Nick Dandoulakis
  • 42,588
  • 16
  • 104
  • 136
3

To add to the other answers: Lua does have a boolean data type, where C does not. C uses numbers for that, where 0 is false and everything else is true.

However, to format a boolean in a String in Lua,

local text = string.format("bool is %d", truth)

gets (at least in Hammerspoon):

bad argument #2 to 'format' (number expected, got boolean)

You can instead use %s for booleans (as for strings):

local text = string.format("bool is %s", truth)
Robert
  • 7,394
  • 40
  • 45
  • 64