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 (%d, %s, %f, etc.)
......Values to be formatted according to the format 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

Returns

TypeNameDescription
stringresultFormatted string

Examples

--Basic string formatting
local str = string.format("Hello %s", "World")
engine.print(str) --Hello World
--Integer formatting
local num = string.format("Number: %d", 42)
engine.print(num) --Number: 42
--Multiple values
local result = string.format("%d + %d = %d", 5, 3, 8)
engine.print(result) --5 + 3 = 8
--Floating point with precision
local pi = string.format("Pi: %.2f", math.pi)
engine.print(pi) --Pi: 3.14
--More decimal places
local precise = string.format("%.5f", math.pi)
engine.print(precise) --3.14159
--Padding with zeros
local padded = string.format("%05d", 42)
engine.print(padded) --00042
--Hexadecimal uppercase
local hex = string.format("0x%X", 255)
engine.print(hex) --0xFF
--Hexadecimal lowercase
local hexLower = string.format("0x%x", 255)
engine.print(hexLower) --0xff
--Scientific notation
local sci = string.format("%e", 1234.5)
engine.print(sci) --1.234500e+03
--Character from byte value
local char = string.format("%c", 65)
engine.print(char) --A
--String with width (right aligned)
local aligned = string.format("%10s", "right")
engine.print(aligned) --     right
--String with width (left aligned)
local leftAligned = string.format("%-10s", "left")
engine.print(leftAligned) --left      
--Quoted string (escapes special characters)
local quoted = string.format("%q", "hello\nworld")
engine.print(quoted) --"hello\nworld"
--Combining multiple specifiers
local info = string.format("Name: %s, Age: %d, Score: %.1f%%", "Alice", 25, 95.5)
engine.print(info) --Name: Alice, Age: 25, Score: 95.5%
--Octal
local oct = string.format("%o", 8)
engine.print(oct) --10
--Percent sign
local percent = string.format("Progress: 100%%")
engine.print(percent) --Progress: 100%

On this page