string.format()

The string.format() function creates a formatted string using a format string and optional arguments. It is useful for formatting numbers, strings, and other values in a structured way.

Syntax

string.format(formatString, ...)

Parameters

  • Name
    formatString
    Type
    string
    Description

    A string specifying the desired format. It can include format specifiers for values to insert.

  • Name
    ...
    Type
    varargs
    Description

    A variable number of arguments to format and insert into the formatString.

Return Value

Returns the formatted string after applying the format specifiers.

Common Format Specifiers

SpecifierDescription
%dFormats a number as an integer.
%fFormats a number as a floating-point value.
%sInserts a string.
%x/%XFormats a number as a hexadecimal (lower/uppercase).
%e/%EFormats a number in scientific notation.
%%Inserts a literal % character.

Examples

Example 1: Basic Formatting

Format a string with a number and a word.

Example 1

local formatted = string.format("I have %d apples and %s oranges.", 5, "seven")
print(formatted)

-- Output: I have 5 apples and seven oranges.

Example 2: Floating-point Formatting

Control the number of decimal places for a float.

Example 2

local pi = math.pi
local formatted = string.format("Value of pi: %.2f", pi)
print(formatted)

-- Output: Value of pi: 3.14

Example 3: Hexadecimal Formatting

Convert numbers to hexadecimal.

Example 3

local number = 255
local formatted = string.format("Hexadecimal: %x", number)
print(formatted)

-- Output: Hexadecimal: ff

Example 4: Scientific Notation

Format numbers in scientific notation.

Example 4

local number = 123456789
local formatted = string.format("Scientific: %e", number)
print(formatted)

-- Output: Scientific: 1.234568e+08

Example 5: Literal Percent Sign

Include a % character in the output.

Example 5

local formatted = string.format("Progress: %d%% complete", 75)
print(formatted)

-- Output: Progress: 75% complete

Use Cases

  • Dynamic Strings: Insert variables into a string in a structured way.
  • Formatting Numbers: Control how numbers are displayed, including decimals or scientific notation.
  • Hexadecimal Conversion: Represent numbers in base-16 for specific applications.
  • Data Reports: Create neatly formatted output for tables or logs.

See also

  • string.gsub(): Replace substrings in a string, often used in conjunction with string.format() for dynamic replacements.
  • string.rep(): Repeat a string multiple times, useful for formatting or padding.
  • string.sub(): Extract substrings, which can be helpful for dynamic formatting.

Was this page helpful?

Table of Contents