0Pricing
Lua Academy · Lesson

string.format for Output

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

string.format for Output is a free Lua Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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

%f and %e for Floats

%f formats in fixed-point notation; %e in scientific notation; %g picks whichever is shorter. A precision specifier (e.g. %.2f) controls decimal places. Default precision is 6.

print(string.format("%.2f",  3.14159)) -- 3.14
print(string.format("%10.3f", 3.14))   --      3.140
print(string.format("%e", 12345.678))  -- 1.234568e+04
print(string.format("%.2e", 0.001))    -- 1.00e-03
print(string.format("%g", 100.0))      -- 100

%s for Strings

%s inserts a string. Non-string values are converted with tostring. Width and alignment work as with numbers. %q quotes a string in a Lua-readable format (with escapes), useful for serialization.

print(string.format("%-10s|", "hi"))   -- hi        |
print(string.format("%10s|", "hi"))    --         hi|
print(string.format("%.3s", "hello"))  -- hel (truncate)
print(string.format("%q", 'say "hi"'))-- "say \"hi\""
print(string.format("%s=%s", "key","val")) -- key=val

%x and %o for Other Bases

%x formats an integer in hexadecimal (lowercase); %X in uppercase hex; %o in octal; %u as unsigned integer. These are useful for bitmask display, color codes, and low-level programming.

print(string.format("%x",  255))   -- ff
print(string.format("%X",  255))   -- FF
print(string.format("%#x", 255))   -- 0xff (with prefix)
print(string.format("%o",  8))     -- 10 (octal)
print(string.format("%08x", 0xDEAD)) -- 0000dead

Multiple Values

Pass as many arguments as there are format specifiers. Argument count must match — too few causes an error; extras are ignored. Use format strings to build structured output like tables, logs, or reports.

local function printRow(name, score, grade)
  print(string.format("%-12s  %3d  %s", name, score, grade))
end

printRow("Alice",    95, "A")
printRow("Bob",      87, "B")
printRow("Carol",    91, "A")
-- Alice         95  A
-- Bob           87  B
-- Carol         91  A

Building Format Templates

Store format strings as constants for reuse. This keeps output consistent and makes it easy to change the format in one place. String format is the foundation of logging, CSV output, and report generation.

local LOG_FMT = "[%s] %s: %s"

local function log(level, module, msg)
  print(string.format(LOG_FMT, level, module, msg))
end

log("INFO",  "server", "started on port 8080")
log("WARN",  "db",     "connection pool low")
log("ERROR", "auth",   "token expired")

Padding and Alignment

Use width specifiers for aligned output. Positive width right-aligns; negative left-aligns. This is especially useful for tables and reports where columns should line up. Combine with string.rep for divider lines.

local fmt = "%-15s %6s %8s"
print(string.format(fmt, "Name", "Score", "Grade"))
print(string.rep("-", 31))
local data = {{"Alice",95,"A"},{"Bob",87,"B"},{"Dave",78,"C"}}
for _, r in ipairs(data) do
  print(string.format(fmt, r[1], r[2], r[3]))
end

%c and %% Literals

%c converts an integer to the corresponding ASCII character. %% produces a literal percent sign. These are useful for generating special characters or including % in format strings.

print(string.format("%c%c%c", 76, 117, 97))  -- Lua
print(string.format("100%%"))                -- 100%
print(string.format("%.1f%%", 87.5))         -- 87.5%

-- Build a progress bar
local pct = 65
local filled = math.floor(pct / 5)
local bar = "[" .. string.rep("#",filled) .. string.rep(".",20-filled) .. "]"
print(bar .. " " .. pct .. "%")

string.format vs tostring

Use tostring for simple any-type conversion; use string.format for precision control, padding, and multi-value formatting. string.format("%s", val) calls tostring internally for string conversions.

-- tostring: simple, any type
print(tostring(3.14))      -- 3.14
print(tostring(true))      -- true
print(tostring(nil))       -- nil

-- string.format: precision + structure
print(string.format("%.2f", 3.14159))  -- 3.14
print(string.format("%d", 255))        -- 255
-- print(string.format("%d", true))    -- ERROR

Quick Check

What does string.format("%05.2f", 3.1) produce?

Recap: string.format

Summary:

  • %s string, %d integer, %f float, %x hex
  • Width: %10d right-align, %-10d left-align, %010d zero-pad
  • Precision: %.2f (2 decimal places), %.3s (3 chars)
  • %q quotes a string for Lua parsing
  • %% literal percent sign

Frequently asked questions

Is the “string.format for Output” lesson free?

Yes — the full text of “string.format for Output” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.

What will I learn in “string.format for Output”?

Format strings with %s, %d, %f, and other format specifiers. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “string.format for Output” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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