string.format

The function string.format returns a formatted string replacing format specifiers with variables.
Function syntax is: string.format(<string with n specifiers>, arg1, arg2, arg3, ... , argn)
A format specifier looks like this[1]:
%[flags][width][.precision]specifier

Integers

string.format("string with integer: %d", 123)
--> "string with integer: 123"

string.format("in hexadecimal: %x %X",123,459)
--> "in hexadecimal: 7b 1CB"

string.format("padded with spaces: %8d", 123)
string.format("padded with spaces: %8d", 12345)
--> "padded with spaces:      123"
--> "padded with spaces:    12345"

string.format("padded with zeros: %06d", 123)
--> "padded with zeros: 000123"

string.format("8bit %02X | 16bit %04X | 32bit %08X", 123, 789, 456789)
--> "8bit 7B | 16bit 0315 | 32bit 0006F855"

Decimals

string.format("string with decimals: %f", 2/11)
--> "string with decimals: 0.181818"

string.format("specify precision: %.3f", 2/11)
--> "specify precision: 0.182"

Aligning Positive and Negative Values

string.format("force sign: %+d",123)
string.format("force sign: %+d",-123)
--> "force sign: +123"
--> "force sign: -123"

string.format("force space: % d",123)
string.format("force space: % d",-123)
--> "force space:  123"
--> "force space: -123"

Various

string.format("percent sign: 95%%")
--> "percent sign: 95%"

string.format("insert another %s inside", "string")
--> "insert another string inside"


Rounding

numA = 4.3
numB = 4.7

Down

math.floor(numA)
--> 4
math.floor(numB)
--> 4

Up

math.ceil(numA)
--> 5
math.ceil(numB)
--> 5

Nearest Integer

math.floor(numA + 0.5)
--> 4
math.floor(numB + 0.5)
--> 5


[1] C reference, the length specifier is removed

HomePages/Masterjun/LuaCheatSheet last edited by Masterjun on 1/13/2022 3:52 PM
Page History Latest diff List referrers View Source