Difference between revisions of "String.format"
m (Text replacement - "<source" to "<syntaxhighlight") |
m (Text replacement - "</source>" to "</syntaxhighlight>") |
||
Line 7: | Line 7: | ||
<syntaxhighlight lang="lua"> | <syntaxhighlight lang="lua"> | ||
string.format(formatstring,e1,e2,...) | string.format(formatstring,e1,e2,...) | ||
− | </ | + | </syntaxhighlight> |
The format string follows the same rules as the printf family of standard C functions. The only differences are that the options/modifiers *, l, L, n, p, and h are not supported and that there is an extra option, q. | The format string follows the same rules as the printf family of standard C functions. The only differences are that the options/modifiers *, l, L, n, p, and h are not supported and that there is an extra option, q. | ||
Line 56: | Line 56: | ||
another new line! | another new line! | ||
]] | ]] | ||
− | </ | + | </syntaxhighlight> |
==== Flags ==== | ==== Flags ==== | ||
Line 79: | Line 79: | ||
print(string.format(str, 100)) | print(string.format(str, 100)) | ||
-- There is a 100% chance of rain in Seattle today. | -- There is a 100% chance of rain in Seattle today. | ||
− | </ | + | </syntaxhighlight> |
==== Width ==== | ==== Width ==== | ||
Line 89: | Line 89: | ||
-- Output: Score: 000000015000 | -- Output: Score: 000000015000 | ||
-- The output has 12 digits total, left-padded with zeros | -- The output has 12 digits total, left-padded with zeros | ||
− | </ | + | </syntaxhighlight> |
==== Precision ==== | ==== Precision ==== | ||
Line 110: | Line 110: | ||
print(string.format(str, "Pi", math.pi)) | print(string.format(str, "Pi", math.pi)) | ||
-- Output: Once upon a time, there was a dragon named Pi and it had 3.14159265 horns. | -- Output: Once upon a time, there was a dragon named Pi and it had 3.14159265 horns. | ||
− | </ | + | </syntaxhighlight> |
=== Parameters === | === Parameters === | ||
Line 132: | Line 132: | ||
-- or | -- or | ||
local mycolorstring2 = ("%x"):format(mycolor) --> "ff" | local mycolorstring2 = ("%x"):format(mycolor) --> "ff" | ||
− | </ | + | </syntaxhighlight> |
{{String}} | {{String}} |
Latest revision as of 14:33, 13 July 2023
Available since: Gideros 2011.6
Class: string
Description
Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string).
string.format(formatstring,e1,e2,...)
The format string follows the same rules as the printf family of standard C functions. The only differences are that the options/modifiers *, l, L, n, p, and h are not supported and that there is an extra option, q.
The q option formats a string in a form suitable to be safely read back by the Lua interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written. For instance, the call
string.format('%q', 'a string with "quotes" and \n new line')
will produce the string:
"a string with \"quotes\" and \ new line"`
The options c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as argument, whereas q and s expect a string.
This function does not accept string values containing embedded zeros, except as arguments to the q option.
You can convert variables into user-friendly strings of text using the string.format() function. The function requires the following format:
%[flags][width].[precision][specifier]
Specifiers
The most important part of string formatting is the specifiers.
- Specifier Accepts Outputs Example Output
- c integer 3
- d or i integer Decimal representation. 321
- e or E float Scientific notation using e or E. 3.296e2 3.296E2
- f float 3231.1231
- g or G float The shorter of e/E and f. 3E14 3e14
- o integer Octal representation. 610
- q string String in a form suitable to be safely read back by the Lua interpreter. The string is written between double quotes and all double quotes, new lines, embedded zeros, and backslashes are correctly escaped. "print(\"Hi\")"
- s string Hello world!
- u integer Decimal representation. 3131
- x or X integer Hexadecimal representation. 7fa 7FA
- % % followed by another % will return the % sign itself. %
local str = "The magic word is %s"
print(string.format(str, "Gideros"))
-- The magic word is Gideros
local str = "The magic word is %q"
print(string.format(str, "Gideros"))
-- The magic word is "Gideros"
local str = "Skip to \na new line and \nanother new line!"
print(string.format(str, "%q"))
--[[ Output:
Skip to
a new line and
another new line!
]]
Flags
- Flag Description
- - Left-justify the given field width (see Width below). Right justification is the default.
- + Forces a "+" sign to precede a number. Has no effect on negative numbers.
- (space) One blank space is inserted before a positive number, while negative numbers are unaffected. This is useful for making positive and negative numbers vertically align in a visual stacked list.
- When used with o and x/X, writes a 0 (octal) or 0x/0X (hex) before values other than zero.
- When used with e/E and f, forces the output to contain a decimal point, even if no digits would follow (by default, no decimal point is written if no digits follow).
- When used with g or G, the result is the same as with e or E but trailing zeros are not removed.
- 0 Left-pads the number with zeros instead of empty spaces (see Width below).
local str = "%-10d"
print(string.format(str, 300) .. "]")
-- 300 ]
-- There are 7 spaces between '300' and ']'
local str = "%+i versus %+i"
print(string.format(str, 300, -300)) -- +300 versus -300
local str = "There is a% i%% chance of rain in Seattle today."
print(string.format(str, 100))
-- There is a 100% chance of rain in Seattle today.
Width
- Width Description
- (number) Minimum number of characters to return. If the number of characters to be formatted is less than this number, the result is padded with blank spaces.
local str = "%012i"
print("Score: " .. string.format(str, 15000))
-- Output: Score: 000000015000
-- The output has 12 digits total, left-padded with zeros
Precision
The default precision is 1. If you give a period without a value, the default is 0.
- Precision Description
- .(number) For integer specifiers (d, i, o, u, x/X), precision specifies the minimum number of digits to be returned. If the value to be formatted is shorter than this number, the result is padded with leading zeros. A precision of 0 means that no character is written for the value 0.
- For e/E and f specifiers, this is the number of digits to be printed after the decimal point.
- For g/G specifiers, this is the maximum number of digits (before the e/E, if present).
- For s, this is the maximum number of characters to be returned.
- For c and q, this has no effect.
-- Add decimal with precision of 2 for a currency output
local str = "$%.2f"
print(string.format(str, 300)) -- Output: $300.00
-- Return first 6 letters of a string
local str = "%.6s"
print(string.format(str, "Giderians")) -- Output: Gideri
local str = "Once upon a time, there was a dragon named %s and it had %.8f horns."
print(string.format(str, "Pi", math.pi))
-- Output: Once upon a time, there was a dragon named Pi and it had 3.14159265 horns.
Parameters
formatstring: (string) the string defining the format of the output
e1: (string) first parameter for the format string optional
e2: (string) second parameter to format string optional
...: (multiple) more optional parameters for format string optional
Examples
Format an hexadecimal (0xRRGGBB) color to a string "0xRRGGBB"
local mycolor = 0x0000ff -- your color in hexadecimal format
-- prints "0x" as regular string, then add converted hex number with 6 leading zeros
local mycolorstring = string.format("0x%06x",mycolor) --> "0x0000ff"
-- or
local mycolorstring = ("0x%06x"):format(mycolor) --> "0x0000ff"
-- converts to hex number only
local mycolorstring2 = string.format("%x",mycolor) --> "ff"
-- or
local mycolorstring2 = ("%x"):format(mycolor) --> "ff"