Vital.sandbox
String

string.format

Shared

Returns a formatted string using format specifiers


Syntax

local result = string.format(format, ...)

Parameters

TypeNameDescription
stringformatFormat string containing specifiers
Refer Specifiers section
......Values to be formatted according to the format string

Returns

TypeNameDescription
stringresultFormatted string

Specifiers

SpecifierDescription
%d / %iSigned decimal integer
%uUnsigned decimal integer
%oUnsigned octal
%xUnsigned hexadecimal (lowercase)
%XUnsigned hexadecimal (uppercase)
%fDecimal floating point
%eScientific notation (lowercase)
%EScientific notation (uppercase)
%gShortest of %e or %f
%GShortest of %E or %f
%cCharacter (from byte value)
%sString
%qQuoted string
%%Literal percent sign

Examples

Format a basic string
local str = string.format("Hello %s", "World")

engine.print("info", str) --'Hello World'
Format an integer
local num = string.format("Number: %d", 42)

engine.print("info", num) --'Number: 42'
Format multiple values in one string
local result = string.format("%d + %d = %d", 5, 3, 8)

engine.print("info", result) --'5 + 3 = 8'
Format a float with fixed decimal precision
local pi = string.format("Pi: %.2f", math.pi)

engine.print("info", pi) --'Pi: 3.14'
Format a float with more decimal places
local precise = string.format("%.5f", math.pi)

engine.print("info", precise) --'3.14159'
Pad an integer with leading zeros
local padded = string.format("%05d", 42)

engine.print("info", padded) --'00042'
Format a number as uppercase hexadecimal
local hex = string.format("0x%X", 255)

engine.print("info", hex) --'0xFF'
Format a number as lowercase hexadecimal
local hexLower = string.format("0x%x", 255)

engine.print("info", hexLower) --'0xff'
Format a number in scientific notation
local sci = string.format("%e", 1234.5)

engine.print("info", sci) --'1.234500e+03'
Format a character from a byte value
local char = string.format("%c", 65)

engine.print("info", char) --'A'
Right-align a string within a fixed width
local aligned = string.format("%10s", "right")

engine.print("info", aligned) --'     right'
Left-align a string within a fixed width
local leftAligned = string.format("%-10s", "left")

engine.print("info", leftAligned) --'left     '
Format a quoted string with escaped characters
local quoted = string.format("%q", "hello\nworld")

engine.print("info", quoted) --'"hello\nworld"'
Combine multiple format specifiers
local info = string.format("Name: %s, Age: %d, Score: %.1f%%", "Alice", 25, 95.5)

engine.print("info", info) --'Name: Alice, Age: 25, Score: 95.5%'
Format a number as octal
local oct = string.format("%o", 8)

engine.print("info", oct) --'10'
Include a literal percent sign
local percent = string.format("Progress: 100%%")

engine.print("info", percent) --'Progress: 100%'

On this page