TExcelTAD
Home › Lua › Lua String Formatting

Lua String Formatting

string.format(fmt, ...) builds a string from a format string with placeholders, similar to C's printf. It is the tool for aligned columns, fixed decimals, padding with zeros and safe quoting.

lua · try it yourself
local name, score, accuracy = "Rin", 1450, 0.8734
print(string.format("%s scored %d points (%.1f%% accuracy)", name, score, accuracy * 100))
print(("%s has %d lives"):format("Kai", 3))
Rin scored 1450 points (87.3% accuracy)
Kai has 3 lives

%% produces a literal percent sign. The method form fmt:format(...) is common.

Conversion specifiers

Specifier Formats Example Result
%d integer (the value must have an exact integer value) ("%d"):format(42) 42
%f float, 6 decimals by default ("%f"):format(1/3) 0.333333
%.Nf float with N decimals ("%.2f"):format(2.5) 2.50
%e scientific notation ("%.2e"):format(12345) 1.23e+04
%g shortest of %f / %e ("%g"):format(0.0001) 0.0001
%x, %X hexadecimal ("%x"):format(255) ff
%o octal ("%o"):format(8) 10
%c character from a byte code ("%c"):format(65) A
%s string (uses tostring) ("%s"):format(true) true
%q a Lua literal that reads back as the same value ("%q"):format("a\"b") "a\"b"
%a hexadecimal float ("%a"):format(1) 0x1p+0
lua · try it yourself
print(string.format("%d | %f | %.2f | %e", 42, 1/3, 2.5, 12345))
print(string.format("%x %X %o %c", 255, 255, 8, 65))
print(string.format("%s %s %s", nil, true, 12.0))
42 | 0.333333 | 2.50 | 1.234500e+04
ff FF 10 A
nil true 12.0

Width, alignment and padding

Between % and the letter you can put flags, a width and a precision:

Form Meaning ("…"):format(7)
%5d right-align in 5 characters 7
%-5d left-align in 5 characters 7
%05d pad with zeros 00007
%+d always show the sign +7
%8.3f width 8, 3 decimals 7.000
%.3s at most 3 characters of a string
lua · try it yourself
local items = {
  { "Notebook", 3, 2.5 },
  { "Pen", 12, 0.8 },
  { "Backpack", 1, 34.99 },
}
print(string.format("%-10s %5s %8s", "Item", "Qty", "Total"))
print(string.rep("-", 25))
for _, it in ipairs(items) do
  print(string.format("%-10s %5d %8.2f", it[1], it[2], it[2] * it[3]))
end
print(string.format("Order #%06d, change %+.2f", 4711, -0.5))
Item         Qty    Total
-------------------------
Notebook       3     7.50
Pen           12     9.60
Backpack       1    34.99
Order #004711, change -0.50

%d needs an integer value

%d accepts floats only when they have an exact integer value (3.0 works, 3.5 doesn't):

lua · try it yourself
print(string.format("%d", 3.0))
print(pcall(string.format, "%d", 3.5))
print(string.format("%d", math.floor(3.5)))
3
false	bad argument #2 to 'string.format' (number has no integer representation)
3

pcall calls a function and catches its error, so we can show the message without stopping the program. Round or floor the value first, or use %.0f.

%q: quoting values safely

%q writes a string as a valid Lua literal with every special character escaped. It is how you generate Lua source code or save data that can be loaded back with load:

lua · try it yourself
local tricky = 'He said "hi"\nthen left\t\\'
local literal = string.format("%q", tricky)
print(literal)

local restored = load("return " .. literal)()
print(restored == tricky)
print(string.format("%q %q", 42, math.mininteger))
"He said \"hi\"\
then left\9\\"
true
42 0x8000000000000000

Notice how %q writes the newline as a backslash followed by a real line break, and the tab as \9. Integers are written so that they read back exactly.

Test yourself

What does string.format("%.2f", 3.14159) return?

  1. 3.14
  2. 3.1
  3. 3.142
  4. 3.14159

How do you print a literal percent sign inside a format string?

  1. \%
  2. %%
  3. %p
  4. %s

What does string.format("%04d", 42) return?

  1. 42
  2. 42
  3. 0042
  4. 4200