Wiki

Clone wiki

Core / string.format

Back to Beyond the Codea in-app reference


FunctionIconFunction-Small.png string.format (formatstring, ...) function

Introduction

The Lua version 5.1 reference documents most of the string.format(formatstring, ...) function. The function returns a formatted version of its variable arguments following the description given in its first argument, which must be a string following the rules below.

Rules for formatstring

The format string can contain format specifiers that are replaced by the values specified in the other arguments, formatted as specified. The format specifiers have the form, where [] indicates an optional part:

%[flags][width][.precision]type

The type part of the specifier is required:

typeOutputExamples
d or iSigned decimal integer1234
uUnsigned decimal integer1234
oUnsigned octal2322
xUnsigned hexadecimal integer (lowercase)4d2
XUnsigned hexadecimal integer (uppercase)4D2
fDecimal floating point1234.567749
eScientific notation (lowercase)1.234568e+03
EScientific notation (uppercase)1.234568E+03
gUse the shortest representation: %e or %f1234.57
GUse the shortest representation: %E or %f1234.57
cCharactera
sString of characters1234.57, hello
qFormats a string in a form suitable to be safely read back by Lua: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written.
%%% will print a single %%

The optional flags part of the format specifier:

flagsExplanation
-Left-justify within the given width (see below). Right justification is the default.
+Prefix positive numbers with a plus sign.
(space)Prefix positive numbers with a space.
#For o, x or X types, non-zero values are prefixed with 0, 0x or 0X. For e, E, f, g or G types, it forces the output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
0Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width).

The optional width part of the format specifier is the minimum number of characters to be printed. If necessary, the result is padded with blank spaces but the result is not truncated if the result is larger.

The optional .precision part of the format specifier is a number. . is equivalent to .0.

TypeExplanation of precision
d, i, o, u, x, XThe minimum number of digits to be written. If necessary, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0.
e, E, and fThe number of digits to be printed after the decimal point (6 by default).
g and GThe maximum number of significant digits to be printed.
sThe maximum number of characters to be printed. All are printed by default.

Updated