← Back to Lua Course | Chapter 3: Strings | Lesson 7 of 7

Formatting with string.format

string.format builds text from a template with placeholders like %d, %s and %.2f.

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

lua
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%
Common Mistakes
  1. Passing a float with a fractional part to %d
  2. Forgetting to supply enough arguments for the placeholders
  3. 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

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.