0Pricing
Lua Academy · Lesson

string.format for Output

Format strings with %s, %d, %f, and other format specifiers.

string.format Basics

string.format(fmt, ...) formats values using C-style format specifiers. It returns a formatted string. The format string contains literal text and conversion specifiers starting with %. This is the primary way to produce precise output in Lua.

print(string.format("Hello, %s!", "Lua"))      -- Hello, Lua!
print(string.format("Pi is %.4f", math.pi))   -- Pi is 3.1416
print(string.format("%d items at $%.2f each", 5, 2.99))

%d and %i for Integers

%d and %i format integers. Add a width for padding: %5d right-pads to 5 chars. %-5d left-aligns. %05d pads with zeros. These specifiers truncate floats — use math.floor() first if needed.

print(string.format("%d",  42))       -- 42
print(string.format("%5d", 42))       --    42 (right-aligned)
print(string.format("%-5d|", 42))     -- 42   | (left-aligned)
print(string.format("%05d", 42))      -- 00042
print(string.format("%+d", 42))       -- +42

All lessons in this course

  1. String Basics: Concat and Length
  2. Finding and Extracting Substrings
  3. string.format for Output
  4. string.gsub and string.gmatch
← Back to Lua Academy