View Page Source

Revision (current)
Last Updated by Masterjun on 1/13/2022 3:52 PM
Back to Page

%%TOC%%

!!! 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
%%SRC_EMBED lua
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"
%%END_EMBED
----
!! Decimals
%%SRC_EMBED lua
string.format("string with decimals: %f", 2/11)
--> "string with decimals: 0.181818"

string.format("specify precision: %.3f", 2/11)
--> "specify precision: 0.182"
%%END_EMBED
----
!! Aligning Positive and Negative Values
%%SRC_EMBED lua
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"
%%END_EMBED
----
!! Various
%%SRC_EMBED lua
string.format("percent sign: 95%%")
--> "percent sign: 95%"

string.format("insert another %s inside", "string")
--> "insert another string inside"
%%END_EMBED
----
----
!!! Rounding
%%SRC_EMBED lua
numA = 4.3
numB = 4.7
%%END_EMBED
!! Down
%%SRC_EMBED lua
math.floor(numA)
--> 4
math.floor(numB)
--> 4
%%END_EMBED
!! Up
%%SRC_EMBED lua
math.ceil(numA)
--> 5
math.ceil(numB)
--> 5
%%END_EMBED
!! Nearest Integer
%%SRC_EMBED lua
math.floor(numA + 0.5)
--> 4
math.floor(numB + 0.5)
--> 5
%%END_EMBED
----
----

[1] [http://www.cplusplus.com/reference/cstdio/printf/|C reference], the {{length}} specifier is removed