String
string.format
Shared
Returns a formatted string using format specifiers
Syntax
local result = string.format(format, ...)Parameters
| Type | Name | Description |
|---|---|---|
string | format | Format string containing specifiers (%d, %s, %f, etc.) |
... | ... | Values to be formatted according to the format string |
Specifiers
| Specifier | Description |
|---|---|
%d / %i | Signed decimal integer |
%u | Unsigned decimal integer |
%o | Unsigned octal |
%x | Unsigned hexadecimal (lowercase) |
%X | Unsigned hexadecimal (uppercase) |
%f | Decimal floating point |
%e | Scientific notation (lowercase) |
%E | Scientific notation (uppercase) |
%g | Shortest of %e or %f |
%G | Shortest of %E or %f |
%c | Character (from byte value) |
%s | String |
%q | Quoted string |
%% | Literal percent sign |
Returns
| Type | Name | Description |
|---|---|---|
string | result | Formatted 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%