Lua Strings
A string (String) is a sequence of characters composed of digits, letters, and underscores.
In Lua, a string is a basic data type used to store text data.
Strings in Lua can contain any characters, including letters, digits, symbols, spaces, and other special characters.
Strings in the Lua language can be represented in the following three ways:
-
A sequence of characters between single quotes.
local str1 = 'This is a string.'
local str2 = "This is also a string."
-
A sequence of characters between double quotes.
local str = "Hello, "
str = str .. "World!" -- create a new string and assign it to str print(str) -- output "Hello, World!"
-
[[ The difference between ]] A sequence of characters between the delimiters.
local multilineString = [[
This is a multiline string. It can contain multiple lines of text. No need for escape characters. ]]
print(multilineString)
Examples of strings using the above three methods are as follows:
Example
string1
=
"Lua"
(
""String 1 is""
,
string1
)
string2
=
'runoob.com'
(
"String 2 is"
,
string2
)
string3
=
[["Lua Tutorial"]]
(
"String 3 is"
,
string3
)
The output of the above code is:
"字符串 1 是" Lua
字符串 2 是 runoob.com
字符串 3 是 "Lua 教程"
String Length Calculation
In Lua, to calculate the length of a string (that is, the number of characters in the string), you can use the string.len function or the utf8.len function. For strings containing Chinese, utf8.len is generally used; the string.len function is used to calculate the length of strings containing only ASCII.
Example
local
myString
=
"Hello, RUNOOB!"
-- Calculate the length of the string (number of characters)
local
length
=
string.len
(
myString
)
(
length
)
-- Output 14
The myString string in the above example contains only ASCII characters, so the string.len function can accurately return the length of the string.
For strings containing Chinese, use the utf8.len function:
Example
local
myString
=
"Hello, World!"
-- Calculate the length of the string (number of characters)
local
length1
=
utf8
.
len
(
myString
)
(
length1
)
-- output 10
-- The string.len function will give inaccurate results
local
length2
=
string.len
(
myString
)
(
length2
)
-- Output 14
The output is:
10
14
Escape characters are used to represent characters that cannot be displayed directly, such as the backspace key and the carriage return key. For example, to include a double quote in a string you can use \.
All escape characters and their corresponding meanings:
|
Escape character
|
Significance
|
ASCII code value (decimal)
|
|---|---|---|
|
\a
|
Bell (BEL)
|
007
|
|
\b
|
Backspace (BS), moves the current position back one column
|
008
|
|
\f
|
Form feed (FF), moves the current position to the start of the next page
|
012
|
|
\n
|
Line feed (LF), moves the current position to the start of the next line
|
010
|
|
\r
|
Carriage return (CR), moves the current position to the start of the current line
|
013
|
|
\t
|
Horizontal tab (HT) (jumps to the next TAB position)
|
009
|
|
\v
|
Vertical tab (VT)
|
011
|
|
\
|
Represents a backslash character '''
|
092
|
|
'
|
Represents a single quote (apostrophe) character
|
039
|
|
"
|
Represents a double quote character
|
034
|
|
\0
|
Null character (NULL)
|
000
|
|
\ddd
|
Any character represented by a 1- to 3-digit octal number
|
Three-digit octal
|
|
\xhh
|
Any character represented by a 1- to 2-digit hexadecimal number
|
Two-digit hexadecimal
|
String Operations
Lua provides many methods to support string operations:
| No. | Method & Purpose |
|---|---|
| 1 | string.upper(argument): |
| Convert all characters of the string to uppercase. | |
| 2 | string.lower(argument): |
| Convert all characters of the string to lowercase. | |
| 3 | string.gsub(mainString,findString,replaceString,num)
Replace within a string. mainString is the string to operate on, findString is the character to be replaced, replaceString is the replacement character, num is the number of replacements (can be omitted, in which case all are replaced), e.g.: |
> string.gsub("aaaa","a","z",3); zzza 3 | | 4 | string.find (str, substr, [init, [plain]])
Search for the specified content substr in a given target string str. If a matching substring is found, the starting index and ending index of the substring are returned; if it does not exist, nil is returned.
init Specifies the starting position of the search, defaulting to 1; it can be a negative number, indicating a count of characters from the end.
plain Indicates whether to use simple mode, defaulting to false. true performs only a simple substring search, while false indicates using pattern matching with regular expressions.
The following example finds the starting index and ending index positions of the string "Lua":
> string.find("Hello Lua user", "Lua", 1)
7 9
| | 5 | string.reverse(arg)
Reverse String
> string.reverse("Lua")
auL
| | 6 | string.format(...)
Returns a formatted string similar to printf
> string.format("the value is:%d",4)
the value is:4
| | 7 | string.char(arg) and string.byte(arg[,int])
char converts integer numbers into characters and concatenates them; byte converts a character into an integer value (you can specify a character, defaulting to the first character).
> string.char(97,98,99,100)
abcd
> string.byte("ABCD",4)
68
> string.byte("ABCD")
65
>
| | 8 | string.len(arg)
Calculate the length of a string.
string.len("abc")
3
| | 9 | string.rep(string, n)
Returns n copies of the string
> string.rep("abcd",2)
abcdabcd
| | 10 | ..
Concatenates two strings
> print("www.runoob.".."com")
www.runoob.com
| | 11 | string.gmatch(str, pattern)
Returns an iterator function; each call to this function returns the next substring found in string str that matches the description of pattern. If no substring matching the pattern is found, the iterator returns nil.
> for word in string.gmatch("Hello Lua user", "%a+") do print(word) end
Hello
Lua
user
| | 12 | string.match(str, pattern, init)
string.match() only finds the first match in the source string str. The init parameter is optional, specifying the starting point of the search, defaulting to 1.
When a match succeeds, the function returns all the capture results in the match expression; if no capture markers are set, it returns the entire matched string. When there is no successful match, it returns nil.
> = string.match("I have 2 questions for you.", "%d+ %a+")
2 questions
> = string.format("%d, %q", string.match("I have 2 questions for you.", "(%d+) (%a+)"))
2, "questions"
|
String Substring
String substring uses the sub() method.
string.sub() is used to extract a substring; its prototype is:
string.sub(s, i [, j])
Parameter Description:
- s: the string to extract from.
- i: the starting position of the extraction.
- j: the ending position of the extraction, defaulting to -1, the last character.
Example
-- String
local
sourcestr
=
"prefix--runoobgoogletaobao--suffix"
(
"\nOriginal string"
,
string.format
(
"%q"
,
sourcestr
)
)
-- Extract a part, from the 4th to the 15th character
local
first_sub
=
string.sub
(
sourcestr
,
4
,
15
)
(
"\nFirst extraction"
,
string.format
(
"%q"
,
first_sub
)
)
-- Take the string prefix, from the 1st to the 8th character
local
second_sub
=
string.sub
(
sourcestr
,
1
,
8
)
(
"\nSecond extraction"
,
string.format
(
"%q"
,
second_sub
)
)
-- Extract the last 10 characters
local
third_sub
=
string.sub
(
sourcestr
,
10
)
(
"\nThird extraction"
,
string.format
(
"%q"
,
third_sub
)
)
-- Index out of range, output the original string
local
fourth_sub
=
string.sub
(
sourcestr
,
100
)
(
"\nFourth extraction"
,
string.format
(
"%q"
,
fourth_sub
)
)
The execution result of the code above is:
原始字符串 "prefix--runoobgoogletaobao--suffix"
第一次截取 "fix--runoobg"
第二次截取 "prefix--"
第三次截取 "ao--suffix"
第四次截取 "prefix--runoobgoogletaobao--suffix"
String case conversion
The following example demonstrates how to convert the case of a string:
Example
string1
=
"Lua"
;
(
string.upper
(
string1
)
)
(
string.lower
(
string1
)
)
The execution result of the code above is:
LUA
lua
String Search and Reverse
The following example demonstrates how to search and reverse a string:
Example
string
=
"Lua Tutorial"
-- Search for a string
(
string.find
(
string
,
"Tutorial"
)
)
reversedString
=
string
.
reverse
(
string
)
(
"The new string is"
,
reversedString
)
The execution result of the code above is:
5 12
新字符串为 lairotuT auL
String formatting
Lua provides the string.format() function to generate strings with a specific format. The first parameter of the function is the format, followed by the various data corresponding to each code in the format.
Thanks to the format string, the readability of the resulting long strings is greatly improved. The format of this function is very similar to printf() in the C language.
The following example demonstrates how to format a string:
The format string may contain the following escape codes:
- %c - accepts a number and converts it to the corresponding character in the ASCII table
- %d, %i - accepts a number and converts it to a signed integer format
- %o - accepts a number and converts it to an octal format
- %u - accepts a number and converts it to an unsigned integer format
- %x - accepts a number and converts it to a hexadecimal format, using lowercase letters
- %X - accepts a number and converts it to a hexadecimal format, using uppercase letters
- %e - accepts a number and converts it to scientific notation format, using lowercase e
- %E - accepts a number and converts it to scientific notation format, using uppercase E
- %f - accepts a number and converts it to a floating-point format
- %g(%G) - accepts a number and converts it to the shorter of %e (%E, corresponding to %G) and %f
- %q - accepts a string and converts it to a format that can be safely read by the Lua compiler
- %s - accepts a string and formats it according to the given parameters
To further refine the format, parameters can be added after the % sign. The parameters are read in the following order:
- (1) Sign: a + sign indicates that the numeric escape following it will show a plus sign for positive numbers. By default, only negative numbers show a sign.
- (2) Padding: a 0 used for padding when a string width is specified later. The default padding when omitted is a space.
- (3) Alignment flag: when a string width is specified, the default is right-aligned; adding a - sign changes it to left-aligned.
- (4) Width value
- (5) Decimal places/string truncation: the decimal part n added after the width value. If followed by f (floating-point escape, such as %6.3f), it sets the float to keep only n decimal places; if followed by s (string escape, such as %5.3s), it sets the string to display only the first n characters.
Example
string1
=
"Lua"
string2
=
"Tutorial"
number1
=
10
number2
=
20
-- Basic string formatting
(
string.format
(
"Basic formatting %s %s"
,
string1
,
string2
)
)
-- Date formatting
date
=
2
;
month
=
1
;
year
=
2014
(
string.format
(
"Date formatting %02d/%02d/%04d"
,
date
,
month
,
year
)
)
-- Decimal formatting
(
string.format
(
"%.4f"
,
1
/
3
)
)
The execution result of the code above is:
基本格式化 Lua Tutorial
日期格式化 02/01/2014
0.3333
Other examples:
Example
string.format
(
"%c"
,
83
)
-- Output S
string.format
(
"%+d"
,
17.0
)
-- Output +17
string.format
(
"%05d"
,
17
)
-- Output 00017
string.format
(
"%o"
,
17
)
-- Output 21
string.format
(
"%u"
,
3.14
)
-- Output 3
string.format
(
"%x"
,
13
)
-- Output d
string.format
(
"%X"
,
13
)
-- Output D
string.format
(
"%e"
,
1000
)
-- Output 1.000000e+03
string.format
(
"%E"
,
1000
)
-- Output 1.000000E+03
string.format
(
"%6.3f"
,
13
)
-- Output 13.000
string.format
(
"%q"
,
"One\nTwo"
)
-- Output "One\
-- Two"
string.format
(
"%s"
,
"monkey"
)
-- Output monkey
string.format
(
"%10s"
,
"monkey"
)
-- Output monkey
string.format
(
"%5.3s"
,
"monkey"
)
-- Output mon
Mutual Conversion Between Characters and Integers
The following example demonstrates mutual conversion between characters and integers:
Example
-- Character conversion
-- Convert the first character
(
string.byte
(
"Lua"
)
)
-- Convert the third character
(
string.byte
(
"Lua"
,
3
)
)
-- Convert the first character from the end
(
string.byte
(
"Lua"
,-
1
)
)
-- The second character
(
string.byte
(
"Lua"
,
2
)
)
-- Convert the second character from the end
(
string.byte
(
"Lua"
,-
2
)
)
-- Convert an integer ASCII code to a character
(
string.char
(
97
)
)
The execution result of the code above is:
76
97
97
117
117
a
Other common functions
The following example demonstrates other string operations, such as calculating string length, string concatenation, string replication, etc.:
Example
string1
=
"www."
string2
=
"runoob"
string3
=
".com"
-- Use .. for string concatenation
(
"Concatenated string"
,
string1
..
string2
..
string3
)
-- String length
(
"String length "
,
string.len
(
string2
)
)
-- Replicate the string 2 times
repeatedString
=
string.rep
(
string2
,
2
)
(
repeatedString
)
The execution result of the code above is:
连接字符串 www.runoob.com
字符串长度 6
runoobrunoob
Pattern Matching
Patterns in Lua are described directly using regular strings. They are used by pattern-matching functions string.find, string.gmatch, string.gsub, string.match。
You can also use character classes in a pattern string.
A character class refers to a pattern item that can match any character within a specific set of characters. For example, the character class %d matches any digit. So you can use the pattern %d%d/%d%d/%d%d%d%d to search for dd/mm/yyyy dates in the format:
Example
s
=
"Deadline is 30/05/1999, firm"
date
=
"%d%d/%d%d/%d%d%d%d"
(
string.sub
(
s
,
string.find
(
s
,
date
)
)
)
--> 30/05/1999
The following table lists all the character classes supported by Lua:
A single character (except ^$()%.[]*+-? ): matched against the character itself
- . (dot): matched against any character
- %a: matched against any letter
- %c: matched against any control character (e.g. \n)
- %d: matched against any digit
- %l: matched against any lowercase letter
- %p: matched against any punctuation character
- %s: matched against any whitespace character
- %u: matched against any uppercase letter
- %w: matched against any letter/digit
- %x: matched against any hexadecimal digit
- %z: matched against any character representing 0
- %x (where x is a non-alphanumeric character): matched against the character x. It is mainly used to handle the matching of functional characters (^$()%.[]*+-?) in expressions, e.g. %% matches %
- [several character classes]: matched against any character class contained in []. For example, [%w_] matches any letter/digit, or the underscore symbol (_)
- [^several character classes]: matched against any character class not contained in []. For example, [^%s] matches any non-whitespace character
When the above character classes are written in uppercase, they match any character that is not in that class. For example, %S matches any non-whitespace character. For example, '%A' is a non-letter character:
> print(string.gsub("hello, up-down!", "%A", "."))
hello..up.down. 4
The number 4 is not part of the string result; it is the second value returned by gsub, representing the number of replacements that occurred.
There are some special characters in pattern matching that have special meanings. The special characters in Lua are as follows:
( ) . % + - * ? [ ^ $
'%' is used as the escape character for special characters, so '%.' matches a dot; '%%' matches the character '%'. The escape character '%' can be used not only to escape special characters, but also for all non-letter characters.
A pattern item can be:
- a single character class matches any single character in that class;
- a single character class followed by a '
*', matches zero or more characters of that class. This item always matches the longest possible string; - a single character class followed by a '
+', matches one or more characters of that class. This item always matches the longest possible string; - a single character class followed by a '
-', matches zero or more characters of that class. Unlike the '*' item, this item always matches the shortest possible string; - a single character class followed by a '
?', matches zero or one character of that class. Whenever possible, it matches one; %n, where n can be from 1 to 9; this item matches a substring equal to n the capture (described below) with that number.%bxy, where x and y are two literal characters; this item matches a string that starts with x at the beginning y and ends with , and in which the x and y Preserve are balanced strings. That means, if you read the string from left to right, each time you read a x you increment by +1 , and each time you read a y you increment by -1you decrement by , and the final one at the end that y is the first to bring the count to 0 y. For example, the item%b()can match expressions with balanced parentheses.%f[set], refers to the frontier pattern; this item matches an empty string at a position before a character in set , and where the preceding character at that position does not belong to set . The set set has the meaning described earlier. The start and end points of the matched empty string are calculated as if there were a character '\0' at that position.
Patterns:
Mode refer to a sequence of pattern items. Adding the symbol '^' at the very beginning of a pattern anchors the match to the start of the string. Adding the symbol '$' at the very end of a pattern anchors the match to the end of the string. If '^' and '$' appears in other positions, it has no special meaning and represents only itself.
Captures:
A pattern can have a subpattern enclosed in parentheses; these subpatterns are called captures. When a match succeeds, the substrings of the matched string captured by captures are saved for future use. Captures are numbered in the order of their left parentheses. For example, for the pattern "(a*(.)%w(%s*))" , the part of the string matching "a*(.)%w(%s*)" is saved in the first capture (hence numbered 1); the characters matched by "." are capture number 2, and the part matching "%s*" is capture number 3.
As a special case, an empty capture () captures the current position in the string (which is a number). For example, if the pattern "()aa()" is applied to the string "flaaap" , two captures will be produced: 3 and 5.