Formatting with string.format
string.format builds text from a template with placeholders like %d, %s and %.2f.
In this page:
Formatting with string.format
string.format works like C's printf. Common specifiers are %d for integers, %s for strings, %f for floats with %.2f setting the decimals, %x for hexadecimal and %q for a quoted string. Width and flags such as %5d and %05d pad the output. Use %% to print a percent sign.
Note:
The %s specifier calls tostring, so it works with any value including nil and tables.
Example: Formatting with string.format
print(string.format("%d items", 3))
print(string.format("%s is %d years", "Ann", 30))
print(string.format("%.2f", 3.14159))
print(string.format("[%5d] [%-5d] [%05d]", 42, 42, 42))
print(string.format("%x %X %o", 255, 255, 8))
print(string.format("%q", 'say "hi"'))
print(string.format("%d%%", 50))
-- Output:
-- 3 items
-- Ann is 30 years
-- 3.14
-- [ 42] [42 ] [00042]
-- ff FF 10
-- "say \"hi\""
-- 50%
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Passing a float with a fractional part to %d
- Forgetting to supply enough arguments for the placeholders
- Writing % without doubling it to print a percent sign
Chapter Summary
- %d is for integers
- %s takes any value
- %.2f fixes decimals
- %% prints a percent sign
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: