Lua Strings
A string is a sequence of characters composed of digits, letters, and underscores.
In Lua, strings are a basic data type used to store text data.
Strings in Lua can contain any character, including letters, digits, symbols, spaces, and other special characters.
In Lua, strings can be expressed 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!" -- 创建一个新的字符串并将其赋值给str print(str) -- 输出 "Hello, World!"
[[and]]A sequence of characters between [[ and ]].
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 ways are as follows:
Example
print("\"String 1 is\"",string1)
string2 = 'example.com'
print("String 2 is",string2)
string3 = [[Lua Tutorial]]
print("String 3 is",string3)
The output of the above code execution is:
"字符串 1 是" Lua 字符串 2 是 example.com 字符串 3 是 "Lua 教程"
String Length Calculation
In Lua, to calculate the length of a string (i.e., the number of characters in the string), you can usestring.lenfunction orutf8.lenfunction, and for strings containing Chinese, generally useutf8.len,string.lenThe function is used to calculate the length of strings containing only ASCII characters.
Example
-- Calculate the length of the string (number of characters)
local length = string.len(myString)
print(length) -- Output 14
In the above example, the myString string contains only ASCII characters, sostring.lenthe function can accurately return the length of the string.
For strings containing Chinese, useutf8.lenfunction:
Example
-- Calculate the length of the string (number of characters)
local length1 = utf8.len(myString)
print(length1) -- Output 10
-- The string.len function will cause inaccurate results
local length2 = string.len(myString)
print(length2) -- Output 14
The output result is:
10 14
Escape characters are used to represent characters that cannot be displayed directly, such as the backspace key, carriage return, etc. For example, to include double quotes in a string, you can use\。
All escape characters and their corresponding meanings:
Escape character
| Meaning
| ASCII value (decimal)
|
\a
| Bell (BEL)
| 007
|
\b
| Backspace (BS), moves the current position to the previous column
| 008
|
\f
| Form feed (FF), moves the current position to the beginning of the next page
| 012
|
\n
| Line feed (LF), moves the current position to the beginning of the next line
| 010
|
\r
| Carriage return (CR), moves the current position to the beginning of the current line
| 013
|
\t
| Horizontal tab (HT) (jump 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:
| Serial number | Method & Purpose |
|---|---|
| 1 | string.upper(argument): Convert the entire string to uppercase letters. |
| 2 | string.lower(argument): Convert the entire string to lowercase letters. |
| 3 | string.gsub(mainString,findString,replaceString,num) Replace within a string. mainString is the string to be operated on, findString is the character to be replaced, replaceString is the replacement character, num is the number of replacements (can be ignored, then all are replaced), for example:
> string.gsub("aaaa","a","z",3);
zzza 3
|
| 4 | string.find (str, substr, [init, [plain]]) In a specified target string str, search for the specified content substr. If a matching substring is found, the starting and ending indices of the substring are returned; if it does not exist, nil is returned. initSpecifies the starting position of the search, defaulting to 1. It can be a negative number, indicating the number of characters counted from the end. plainIndicates whether to use plain mode, defaulting to false. true only performs a simple substring search operation, false means using regular expression pattern matching. The following example finds the starting and ending index positions of the string "Lua":
> string.find("Hello Lua user", "Lua", 1)
7 9
|
| 5 | string.reverse(arg) String reversal
> 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 to characters and concatenates them, byte converts characters to integer values (you can specify a particular 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 | .. Concatenate two strings
> print("www.example.".."com")
www.example.com
|
| 11 | string.gmatch(str, pattern) Returns an iterator function. Each time this function is called, it returns the next substring found in the string str that matches the pattern description. If the string described by the parameter pattern is not found, the iterator function 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 seeks the first match in the source string str. The parameter init is optional, specifying the starting point of the search process, defaulting to 1. On a successful match, the function returns all capture results in the matching 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 extraction 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 be extracted.
- i: the starting position for extraction.
- j: the ending position for extraction, defaulting to -1, the last character.
Example
-- String
local sourcestr = "prefix--examplegoogletaobao--suffix"
print("\nOriginal string ", string.format("%q", sourcestr))
-- Extract part, from the 4th to the 15th
local first_sub = string.sub(sourcestr, 4, 15)
print("\nFirst extraction ", string.format("%q", first_sub))
-- Take the string prefix, from the 1st to the 8th
local second_sub = string.sub(sourcestr, 1, 8)
print("\nSecond extraction ", string.format("%q", second_sub))
-- Extract the last 10 characters
local third_sub = string.sub(sourcestr, -10)
print("\nThird extraction ", string.format("%q", third_sub))
-- Index out of range, output the original string
local fourth_sub = string.sub(sourcestr, -100)
print("\nFourth extraction ", string.format("%q", fourth_sub))
The output of the above code execution is:
原始字符串 "prefix--examplegoogletaobao--suffix" 第一次截取 "fix--exampleg" 第二次截取 "prefix--" 第三次截取 "ao--suffix" 第四次截取 "prefix--examplegoogletaobao--suffix"
String Case Conversion
The following example demonstrates how to convert the case of strings:
Example
print(string.upper(string1))
print(string.lower(string1))
The output of the above code execution is:
LUA lua
String Search and Reverse
The following example demonstrates how to perform search and reverse operations on strings:
Example
-- Search for string
print(string.find(string,"Tutorial"))
reversedString = string.reverse(string)
print("The new string is",reversedString)
The output of the above code execution is:
5 12 新字符串为 lairotuT auL
String Formatting
Lua providesstring.format()a function to generate strings with a specific format. The first parameter of the function is the format, followed by various data corresponding to each code in the format.
Due to the existence of the format string, the readability of the resulting long strings is greatly improved. The format of this function is very similar to printf() in C.
The following example demonstrates how to perform formatting operations on strings:
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 - accept a number and convert 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 floating-point format
- %g(%G) - accepts a number and converts it to the shorter format 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 following numeric escape will make positive numbers display a positive sign. By default, only negative numbers show a sign.
- (2) Placeholder: A 0, used for padding when a string width is specified afterwards. If not filled, the default placeholder is a space.
- (3) Alignment flag: When a string width is specified, the default is right alignment; adding a - sign changes it to left alignment.
- (4) Width value
- (5) Decimal places / string truncation: The fractional part n added after the width value. If followed by f (floating-point escape, e.g., %6.3f), it sets the float to keep only n decimal places; if followed by s (string escape, e.g., %5.3s), it sets the string to display only the first n characters.
Example
string2 = "Tutorial"
number1 = 10
number2 = 20
-- Basic string formatting
print(string.format("Basic formatting %s %s",string1,string2))
-- Date formatting
date = 2; month = 1; year = 2014
print(string.format("Date formatting %02d/%02d/%04d", date, month, year))
-- Decimal formatting
print(string.format("%.4f",1/3))
The result of executing the above code is:
基本格式化 Lua Tutorial 日期格式化 02/01/2014 0.3333
Other examples:
Example
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
Character and Integer Conversion
The following example demonstrates converting between characters and integers:
Example
-- Convert the first character
print(string.byte("Lua"))
-- Convert the third character
print(string.byte("Lua",3))
-- Convert the last character
print(string.byte("Lua",-1))
-- The second character
print(string.byte("Lua",2))
-- Convert the second-to-last character
print(string.byte("Lua",-2))
-- Convert an integer ASCII code to a character
print(string.char(97))
The result of executing the above code 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
string2 = "example"
string3 = ".com"
-- Use .. for string concatenation
print("Concatenated string",string1..string2..string3)
-- String length
print("String length ",string.len(string2))
-- Copy the string 2 times
repeatedString = string.rep(string2,2)
print(repeatedString)
The result of executing the above code is:
连接字符串 www.example.com 字符串长度 6 exampleexample
Matching Patterns
Match patterns in Lua are described directly with regular strings. They are used in pattern-matching functionsstring.find, string.gmatch, string.gsub, string.match。
You can also use character classes in pattern strings.
A character class refers to a pattern item that can match any character in a specific character set. For example, the character class%dmatches any digit. So you can use the pattern string%d%d/%d%d/%d%d%d%dto searchdd/mm/yyyydates in the format:
Example
date = "%d%d/%d%d/%d%d%d%d"
print(string.sub(s, string.find(s, date))) --> 30/05/1999
The following table lists all character classes supported by Lua:
A single character (except^$()%.[]*+-?): matches the character itself
- . (dot): matches any character
- %a: matches any letter
- %c: matches any control character (e.g., \n)
- %d: matches any digit
- %l: matches any lowercase letter
- %p: matches any punctuation
- %s: matches any whitespace character
- %u: matches any uppercase letter
- %w: matches any alphanumeric character
- %x: matches any hexadecimal digit
- %z: matches any character representing 0
- %x (where x is a non-alphanumeric character): matches the character x. Mainly used to handle matching of characters with special functions in expressions (^$()%.[]*+-?), e.g., %% matches %
- [several character classes]: matches any character class contained in []. For example, [%w_] matches any letter/digit or the underscore symbol (_)
- [^several character classes]: matches 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 not in that character class. For example, %S matches any non-whitespace character. For example, '%A' matches non-letter characters:
> 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 result returned by gsub, representing the number of substitutions that occurred.
In pattern matching, there are some special characters 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-alphabetic characters.
Pattern items 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 entry always matches the longest possible string; - A single character class followed by a '
+', matches one or more characters of that class. This entry always matches the longest possible string; - A single character class followed by a '
-', matches zero or more characters of that class. Unlike '*', this entry always matches the shortest possible string; - A single character class followed by a '
?', matches zero or one character of that class. If possible, it will match one; -
%n, wherencan be from 1 to 9; this entry matches a substring equal to thennumbered capture (described below). -
%bxy, wherexandyare two explicit characters; this entry matches a string that starts withxand ends withy, and in whichxandyremainsbalancedstring.xJust+1This means, if you read this string from left to right, for each time you read ayJust-1, and read ay,ythe one at the final end%b(). -
%f[set]can match an expression with balanced parentheses., refers tofrontier patternset; this entry matches an empty string locatedsetbefore a character in [set],set.\0has the same meaning as described earlier.
' as if.
Pattern:Pattern^refers to a sequence of pattern items.$' will anchor the match at the beginning of the string.^' will anchor the matching process at the end of the string.$' and '
' appear in other positions, they have no special meaning and represent themselves.
Captures:A pattern can enclose a sub-pattern with parentheses;captures.captures"(a*(.)%w(%s*))"The substrings in the matched string are saved for future use."a*(.)%w(%s*)",.the part is stored in the first capture%s*the matched character is capture 2,
the part matched is capture 3.()As a special case, an empty capture"()aa()"captures the current position in the string (which is a number)."flaaap"applied to the string