🎓 A1Learner
🔍
0 of 47 lessons completed

Lua String Format

string.format is a Lua tool that builds a string by filling placeholders in a pattern with values. The pattern shows exactly where each value belongs.

Pad an ID number with %05d

The 05 in the placeholder pads a short number with zeros. The value 42 fills a width of five characters.

print(string.format("ID: %05d", 42))
print(string.format("ID: %05d", 7))

Show a price with %.2f

The %.2f placeholder always shows two digits after the decimal point. It suits prices and other money values.

print(string.format("Price: $%.2f", 3.5))
print(string.format("Price: $%.2f", 19.9))

Line up labels with %10s

A width in %10s pads a short string with spaces on the left. Two labels of different lengths then end in the same column.

print(string.format("%10s %d", "Apples", 12))
print(string.format("%10s %d", "Bananas", 7))

Example

local breadPrice = string.format("$%.2f", 3.5)
local milkPrice = string.format("$%.2f", 2.25)
local eggPrice = string.format("$%.2f", 4.0)
print(string.format("%10s %6s", "Bread", breadPrice))
print(string.format("%10s %6s", "Milk", milkPrice))
print(string.format("%10s %6s", "Eggs", eggPrice))

Key points

  • string.format: a tool that builds a string from a pattern and a list of values.
  • Placeholder: a code in the pattern that marks where one value will go.
  • %d: the placeholder for a whole number value.
  • %s: the placeholder for a string value.
  • %.2f: the placeholder for a decimal number shown with exactly two digits after the point.
  • %05d: a whole number placeholder padded with leading zeros to a width of five.
  • Width: a number inside a placeholder, such as the 10 in %10s, that reserves space and pads with spaces.

In this example, each price is first built with %.2f so it shows exactly two decimal digits. Each receipt line then places the item name in a width of 10 and the price in a width of 6. The padded widths line the prices up in one column.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which placeholder shows a decimal number with exactly two digits after the point?