Formatting and Converting Strings

Formatting and Converting Strings

String formatting is used to convert variables into a user-friendly string of text. This is done through string.format(), a function which requires specific instructions in this pattern:


The most important part of string formatting is the specifiers.

Specifier Accepts Outputs Example Output
c integer 3
d or i integer Decimal representation. 321
e or E float Scientific notation using e or E. 3.296e2
f float 3231.1231
g or G float The shorter of e/E and f. 3E14
o integer Octal representation. 610
q string String in a form suitable to be safely read back by the Lua interpreter. The string is written between double quotes and all double quotes, new lines, embedded zeros, and backslashes are correctly escaped. "print(\"Hi\")"
s string Hello world!
u integer Decimal representation. 3131
x or X integer Hexadecimal representation. 7fa
% % followed by another % will return the % sign itself. %


Flag Description
- Left-justify the given field width (see Width below). Right justification is the default.
+ Forces a "+" sign to precede a number. Has no effect on negative numbers.
(space) One blank space is inserted before a positive number, while negative numbers are unaffected. This is useful for making positive and negative numbers vertically align in a visual stacked list.
# When used with o and x/X, writes a 0 (octal) or 0x/0X (hex) before values other than zero.
When used with e/E and f, forces the output to contain a decimal point, even if no digits would follow (by default, no decimal point is written if no digits follow).
When used with g or G, the result is the same as with e or E but trailing zeros are not removed.
0 Left-pads the number with zeros instead of empty spaces (see Width below).


Width Description
(number) Minimum number of characters to return. If the number of characters to be formatted is less than this number, the result is padded with blank spaces.


Precision Description
.(number) For integer specifiers (d, i, o, u, x/X), precision specifies the minimum number of digits to be returned. If the value to be formatted is shorter than this number, the result is padded with leading zeros. A precision of 0 means that no character is written for the value 0.
For e/E and f specifiers, this is the number of digits to be printed after the decimal point.
For g/G specifiers, this is the maximum number of digits (before the e/E, if present).
For s, this is the maximum number of characters to be returned.
For c and q, this has no effect.
  • strings
  • coding
  • reference
  • lua