Module string
String standard library.
Lua4z adds the
%g character class
(all printable characters except space), backported from Lua 5.2, to
the string patterns allowed in Lua 5.1.
For more string functions, see the stringx library of the Penlight extension.
Functions
| a2e (s) | Converts the character encoding of a string from ISO8859-1 to EBCDIC code page IBM-1047 regardless of the current locale. |
| atoe (s) | Converts the character encoding of a string from ISO8859-1 to the EBCDIC code page of the current locale. |
| byte (s, i, j) | Returns the internal numerical codes of the characters s[i], s[i+1],
..., s[j]. |
| char (...) | Receives zero or more integers. |
| dump (function) | Returns a string containing a binary representation of the given
function, so that a later loadstring on this string returns a copy of
the function. |
| e2a (s) | Converts the character encoding of a string from EBCDIC to ISO8859-1, interpreting the EBCDIC characters according to code page IBM-1047 regardless of the current locale. |
| etoa (s) | Converts the character encoding of a string from EBCDIC to ISO8859-1, interpreting the EBCDIC characters according to the code page of the current locale. |
| find (s, pattern, init, plain) | Looks for the first match of pattern in the string s. |
| format (formatstring, ...) | Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). |
| gmatch (s, pattern) | Returns an iterator function that, each time it is called, returns the
next captures from pattern over string s. |
| gsub (s, pattern, repl, n) | Returns a copy of s in which all (or the first n, if given)
occurrences of the pattern have been replaced by a replacement string
specified by repl, which can be a string, a table, or a function. |
| len (s) | Receives a string and returns its length. |
| left (s, length, pad) | Gets a substring starting from the left side of a string. |
| lower (s) | Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. |
| match (s, pattern, init) | Looks for the first match of pattern in the string s. |
| rep (s, n) | Returns a string that is the concatenation of n copies of the string
s. |
| reverse (s) | Returns a string that is the string s reversed. |
| right (s, length, pad) | Gets a substring starting from the right side of a string. |
| split (s, delimiters) | Splits a string at delimiters. |
| sub (s, i, j) | Returns the substring of s that starts at i and continues until
j; i and j can be negative. |
| substr (s, n, length, pad) | Gets a substring starting from the nth character of a string. |
| subword (s, n, length) | Gets words starting from the nth word of a string. |
| upper (s) | Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. |
| word (s, n) | Gets the nth word from a string. |
| wordindex (s, n) | Finds the start position of the nth word in a string. |
| wordlength (s, n) | Gets the length of the nth word in a string. |
| wordpos (word, s, start) | Finds a word in a string. |
| words (s) | Counts the words in a string. |
| x2c (hexstring) | Converts a string of characters that represent hexadecimal EBCDIC code points into the corresponding string of EBCDIC characters. |
Functions
- a2e (s)
-
Converts the character encoding of a string
from ISO8859-1
to EBCDIC code page IBM-1047 regardless of the current locale.
Compare with atoe, which is sensitive to the current locale.
Parameters:
- s string An ISO8859-1 character string.
See also:
- atoe (s)
-
Converts the character encoding of a string
from ISO8859-1
to the EBCDIC code page of the current locale.
Compare with a2e, which is not sensitive to the current locale.
Parameters:
- s string An ISO8859-1 character string.
See also:
- byte (s, i, j)
-
Returns the internal numerical codes of the characters
s[i],s[i+1], ...,s[j]. The default value foriis 1; the default value forjisi. Numerical codes are not necessarily portable across platforms.Parameters:
- s
- i
- j
- char (...)
-
Receives zero or more integers. Returns a string with length equal to
the number of arguments, in which each character has the internal numerical
code equal to its corresponding argument.
Numerical codes are not necessarily portable across platforms.
Parameters:
- ...
- dump (function)
-
Returns a string containing a binary representation of the given
function, so that a later
loadstringon this string returns a copy of the function.functionmust be a Lua function without upvalues.Parameters:
- function
- e2a (s)
-
Converts the character encoding of a string
from EBCDIC
to ISO8859-1,
interpreting the EBCDIC characters according to
code page IBM-1047 regardless of the current locale.
Compare with etoa, which is sensitive to the current locale.
Parameters:
- s string An EBCDIC character string.
See also:
- etoa (s)
-
Converts the character encoding of a string
from EBCDIC
to ISO8859-1,
interpreting the EBCDIC characters according to
the code page of the current locale.
Compare with e2a, which is not sensitive to the current locale.
Parameters:
- s string An EBCDIC character string.
See also:
- find (s, pattern, init, plain)
-
Looks for the first match of
patternin the strings. If it finds a match, thenfindreturns the indices ofswhere this occurrence starts and ends; otherwise, it returns nil. A third, optional numerical argumentinitspecifies where to start the search; its default value is 1 and can be negative. A value of true as a fourth, optional argumentplainturns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters inpatternbeing considered "magic". Ifplainis given, theninitmust be given as well. If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.Parameters:
- s
- pattern
- init
- plain
- format (formatstring, ...)
-
Returns a formatted version of its variable number of arguments following
the description given in its first argument (which must be a string). The
format string follows the same rules as the
printffamily of standard C functions. The only differences are that the options/modifiers*,l,L,n,p, andhare not supported and that there is an extra option,q. Theqoption 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 callstring.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, andxall expect a number as argument, whereasqandsexpect a string. This function does not accept string values containing embedded zeros, except as arguments to theqoption.Parameters:
- formatstring
- ...
- gmatch (s, pattern)
-
Returns an iterator function that, each time it is called, returns the
next captures from
patternover strings. Ifpatternspecifies no captures, then the whole match is produced in each call. As an example, the following loops = "hello world from Lua" for w in string.gmatch(s, "%a+") do print(w) end
will iterate over all the words from string
s, printing one per line. The next example collects all pairskey=valuefrom the given string into a table:t = {} s = "from=world, to=Lua" for k, v in string.gmatch(s, "(%w+)=(%w+)") do t[k] = v endFor this function, a '
^' at the start of a pattern does not work as an anchor, as this would prevent the iteration.Parameters:
- s
- pattern
- gsub (s, pattern, repl, n)
-
Returns a copy of
sin which all (or the firstn, if given) occurrences of thepatternhave been replaced by a replacement string specified byrepl, which can be a string, a table, or a function.gsubalso returns, as its second value, the total number of matches that occurred.If
replis a string, then its value is used for replacement. The character%works as an escape character: any sequence inreplof the form%n, with n between 1 and 9, stands for the value of the n-th captured substring (see below). The sequence%0stands for the whole match. The sequence%%stands for a single%.If
replis a table, then the table is queried for every match, using the first capture as the key; if the pattern specifies no captures, then the whole match is used as the key.If
replis a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order; if the pattern specifies no captures, then the whole match is passed as a sole argument.If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).
Here are some examples:
x = string.gsub("hello world", "(%w+)", "%1 %1") --> x="hello hello world world" x = string.gsub("hello world", "%w+", "%0 %0", 1) --> x="hello hello world" x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") --> x="world hello Lua from" x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv) --> x="home = /home/roberto, user = roberto" x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) return loadstring(s)() end) --> x="4+5 = 9" local t = {name="lua", version="5.1"} x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t) --> x="lua-5.1.tar.gz"
Parameters:
- s
- pattern
- repl
- n
- len (s)
-
Receives a string and returns its length. The empty string
""has length 0. Embedded zeros are counted, so"a\000bc\000"has length 5.Parameters:
- s
- left (s, length, pad)
-
Gets a substring starting from the left side of a string.
Parameters:
- s string The original string.
- length int The number of characters to return. Must be a positive integer or zero.
- pad string A pad character. Default is a blank.
Returns:
-
A string of
lengthcharacters starting from the left side ofs.If the original string contains less than
lengthcharacters, the returned string is padded on the right withpadcharacters.If you omit
length, the function returns the original string.See also:
Usage:
local a = string.left("Ellipsis", 2) --> "El" local b = string.left("Ellip", 8, ".") --> "Ellip..." local s = "Ellipsis" local c = s1:left(s1:len() + 3, ".") --> "Ellipsis..." local length = 8 local d = string.left("Name", length) --> "Name " (padded) local e = string.left("Alexander", length) --> "Alexande" (truncated)
- lower (s)
-
Receives a string and returns a copy of this string with all uppercase
letters changed to lowercase. All other characters are left unchanged. The
definition of what an uppercase letter is depends on the current locale.
Parameters:
- s
- match (s, pattern, init)
-
Looks for the first match of
patternin the strings. If it finds one, thenmatchreturns the captures from the pattern; otherwise it returns nil. Ifpatternspecifies no captures, then the whole match is returned. A third, optional numerical argumentinitspecifies where to start the search; its default value is 1 and can be negative.Parameters:
- s
- pattern
- init
- rep (s, n)
-
Returns a string that is the concatenation of
ncopies of the strings.Parameters:
- s
- n
- reverse (s)
-
Returns a string that is the string
sreversed.Parameters:
- s
- right (s, length, pad)
-
Gets a substring starting from the right side of a string.
Parameters:
- s string The original string.
- length int The number of characters to return. Must be a positive integer or zero.
- pad string A pad character. Default is a blank.
Returns:
-
A string of
lengthcharacters starting from the right side ofs.If the original string contains less than
lengthcharacters, the returned string is padded on the left withpadcharacters.If you omit
length, the function returns the original string.See also:
Usage:
local a = string.right("yyyy-mm-ddThh:mm", 5) --> "hh:mm" local b = string.right("A", 2, "0") --> "0A" local c = string.right("0A", 2, "0") --> "0A" (unchanged) local d = ">" .. string.right("foop", 0) .. "<" - "><"
- split (s, delimiters)
-
Splits a string at delimiters.
Parameters:
- s string The string that you want to split.
- delimiters
string
A string of delimiter characters.
Default is
' \t\n': space, tab, newline. Any of the delimiter characters splits the strings.
Returns:
-
An iterator function that, each time it is called, returns the next split element.
Usage:
-- Print the number and name of each day of the week. -- For example: "Day 1: Monday" local week = "Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday" local n = 0 for day in week:split(",") do n = n + 1 print("Day "..n..": "..day) end
- sub (s, i, j)
-
Returns the substring of
sthat starts atiand continues untilj;iandjcan be negative. Ifjis absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the callstring.sub(s,1,j)returns a prefix ofswith lengthj, andstring.sub(s, -i)returns a suffix ofswith lengthi.Parameters:
- s
- i
- j
- substr (s, n, length, pad)
-
Gets a substring starting from the
nth character of a string.Parameters:
- s string The original string.
- n
int
The character position in
sat which to start. Must be a positive integer. - length int The number of characters to return.
- pad string A pad character. Default is a blank.
Returns:
-
A string of
lengthcharacters starting from thenth character ofs.If you omit
length, the returned string consists of the remainder ofs.If
lengthextends past the end ofs, the returned string is padded on the right withpadcharacters.If
nis greater than the length ofs, the returned string consists oflengthpad characters.Usage:
local s = "123456789" local a = string.substr(s, 3, 4) --> "3456" -- Question: Why is 6 afraid of 7? local answer = s:substr(7) --> "789" local b = string.substr(s, 5, 10, "+") --> "56789+++++" local c = string.substr(s, 10, 3, "+") --> "+++"
- subword (s, n, length)
-
Gets words starting from the
nth word of a string.Parameters:
- s string The original string of words.
- n int The number of the first word to get. For example, to start from the third word, specify 3. Must be a positive integer.
- length int The number of words to get.
Returns:
-
A string of up to
lengthblank-delimited words starting from thenth word ofs, ornilifscontains less thannwords.If you omit
length, the returned string contains the remaining words ins.The returned string preserves all blanks between words, but has no leading or trailing blanks.
Usage:
local s = " one giant leap for mankind " local a = s:subword(3) --> "leap for mankind" local b = s:subword(2, 2) --> "giant leap" local b = s:subword(2, 1) --> "giant"
- upper (s)
-
Receives a string and returns a copy of this string with all lowercase
letters changed to uppercase. All other characters are left unchanged. The
definition of what a lowercase letter is depends on the current locale.
Parameters:
- s
- word (s, n)
-
Gets the
nth word from a string.This function is equivalent to
subword(string, n, 1).Parameters:
- s string The original string of words.
- n int The number of the word that you want to get. For example, to get the second word, specify 2. Must be a positive integer.
Returns:
-
A string consisting of the
nth blank-delimited word ins, ornilifscontains less thannwords.The returned string has no leading or trailing blanks.
Usage:
local s = " one small step " local a = s:subword(2) --> "small" local b = s:subword(4) --> nil
- wordindex (s, n)
-
Finds the start position of the
nth word in a string.Parameters:
- s string The original string of words.
- n int The number of the word that you want to find in the string. For example, to find the third word, specify 3. Must be a positive integer.
Returns:
-
An integer that represents the start position of the
nth blank-delimited word ins, or 0 ifscontains less thannwords.Usage:
-- 1 2 -- 123456789012345678901234 <-- Returned value local s = " a sliver of the moon " -- 1 2 3 4 5 <-- Input value (n) -- | local a = s:wordindex(3) --> 12
- wordlength (s, n)
-
Gets the length of the
nth word in a string.Parameters:
- s string The original string of words.
- n int The number of the word that you want to measure. For example, to get the length of the third word, specify 3. Must be a positive integer.
Returns:
-
An integer that represents the length of the
nth blank-delimited word ins, or 0 ifscontains less thannwords.Usage:
local s = "from the planet Earth" local a = s:wordlength(3) --> 6 (length of word 3, "planet")
- wordpos (word, s, start)
-
Finds a word in a string.
Parameters:
- word string The word that you are looking for. Must be a single word without blanks.
- s
string
The string that you want to search; that might contain
word. - start
int
The number of the word in
sat which to start searching forword. Default is 1. Must be a positive integer.
Returns:
-
If
scontainsword, this function returns an integer that represents the number of the word insthat matchesword.If
sdoes not containword, or the value ofwordis invalid (such as a phrase consisting of more than one word), this function returns 0.Usage:
local string = "Three things cannot be long hidden" local word = "things" local a = word:wordpos(string)) --> 2 local a = word:wordpos(string, 3)) --> 0 (not found) word = "thing" -- singular local b = word:wordpos(string)) --> 0 phrase = "long hidden" local c = phrase:wordpos(string)) --> 0 (phrase not allowed)
- words (s)
-
Counts the words in a string.
Parameters:
- s string The string.
Returns:
-
An integer that represents the number of blank-delimited words in
s, where a blank is a space, a tab, or a newline.Usage:
local s1 = "Moonlight drowns out all but the brightest stars." local a = s1:words() --> 8 local s2 = "Commas,are,not,blanks" local b = s2:words() --> 1
- x2c (hexstring)
-
Converts a string of characters that represent hexadecimal EBCDIC code points
into the corresponding string of EBCDIC characters.
Parameters:
- hexstring
string
One or more pair of characters in the range 0 - 9, a - f, A - F.
Each character represents a hexadecimal digit.
Each pair represents an EBCDIC code point.
If
hexstringcontains an odd number of characters, it is padded with a leading 0.
Returns:
-
A string of EBCDIC characters that matches the code points specified by
hexstring.The returned string is half the length of
hexstring(including the leading 0 that might have been added, ifhexstringcontains an odd number of characters).Usage:
-- Create an alias for the string.x2c function local x = string.x2c -- Lua does not require parentheses on function calls with -- only a string argument. -- When combined with the x alias, this feature -- enables us to mimic hex constants: local hexString = x'C8895A' print(hexString) --> "Hi!"
- hexstring
string
One or more pair of characters in the range 0 - 9, a - f, A - F.
Each character represents a hexadecimal digit.
Each pair represents an EBCDIC code point.
