Show Menu
Cheatography

Lua string.format Cheat Sheet by

A quick reference for Lua's standard library string.format function.

Function Call

string.format(formatstring, ...args)

Specifier

Input
Descri­ption
Example
g
Auto
384.63
G
Auto (upper­case)
386
d or i
Signed decimal
-392
u
Unsigned decimal
1483
f
Decimal float
392.65
o
Unsigned octal
610
x
Unsigned hex
7fa
X
Unsigned hex (upper­case)
7FA
a
Hex float
-0xc.9­0fep-2
A
Hex float (upper­case)
-0XC.9­0FEP-2
e
Scientific notation
3.9265e+2
E
Scientific notation (upper­case)
3.9265E+2
c
Character
d
s
String
Hello world
p
Pointer
b8000000
%
Literal "­%"
%
Specifier determines the string format type.
Auto choses between the more reasonable of
e
or
f
.

Q Specifier

The Q specifier does not support flags, width, or precision. It outputs Lua values so that it is valid Lua code.
Booleans are written obviously,
true, false, nil
.
Strings are written with double quotes and escape sequences where necessary.
For example,
string.fo­rma­t('%q', 'a string with "­quo­tes­" and \n new line')
produces:
"a string with \"qu­ote­s\" and \ 

  new line"

Reference

 

Format Specifier

%[flags][width][.precision]specifier
Values are formatted and replaced sequen­tially with ...args.
Only one input can be entered for each argument.
Note the dot before precision.

Flags

'
Group number by thousands.
-
Left justify, see width.
0
Pads with 0s instead of spaces, see width.
+
Adds a + sign for positive numbers.
(space)
Inserts a space if there is no sign.
#
For o, x, X:
    Add 0, 0x, 0X to non-zero numbers.
For a, A, e, E, f, F, g, G:
    Always write a decimal point.

Width

Minimum number of characters to be printed.
If the value is shorter:
 ­ ­ ­ The value is padded, affected by - and 0 flags.
If the value is longer:
 ­ ­ ­ No truncation happens, note minimum.

Precision

For d, i, o, u, x, X (integers):
 ­ ­ ­ ­Minimum number of digits, no truncation happens. If the value is shorter, 0-padding happens on the left side. If set to zero, nothing is written for 0.
For a, A, e, E, f, F (floats):
 ­ ­ ­ ­Number of decimal digits to be printed. Defaults to 6.
For g, G:
 ­ ­ ­ ­Maximum number of signif­icant digits.
For s:
 ­ ­ ­ ­Maximum number of characters to be printed. By default all characters are printed.
Don't forget the dot!
If the period is specified without a value for precision, 0 is assumed.
       
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Roblox: General Scripting Cheat Sheet

          More Cheat Sheets by ambigious

          Lua string patterns Cheat Sheet