Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Lua Strings

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:

local str2 = "This is also a string."

str = str .. "World!" -- create a new string and assign it to str print(str) -- output "Hello, World!"

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"

print

(

""String 1 is""

,

string1

)

string2

=

'runoob.com'

print

(

"String 2 is"

,

string2

)

string3

=

[["Lua Tutorial"]]

print

(

"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

)

print

(

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

)

print

(

length1

)

-- output 10

-- The string.len function will give inaccurate results

local

length2

=

string.len

(

myString

)

print

(

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:

Example

-- String

local

sourcestr

=

"prefix--runoobgoogletaobao--suffix"

print

(

"\nOriginal string"

,

string.format

(

"%q"

,

sourcestr

)

)

-- Extract a part, from the 4th to the 15th character

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 character

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 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"

;

print

(

string.upper

(

string1

)

)

print

(

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

print

(

string.find

(

string

,

"Tutorial"

)

)

reversedString

=

string

.

reverse

(

string

)

print

(

"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:

To further refine the format, parameters can be added after the % sign. The parameters are read in the following order:

Example

string1

=

"Lua"

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 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

print

(

string.byte

(

"Lua"

)

)

-- Convert the third character

print

(

string.byte

(

"Lua"

,

3

)

)

-- Convert the first character from the end

print

(

string.byte

(

"Lua"

,-

1

)

)

-- The second character

print

(

string.byte

(

"Lua"

,

2

)

)

-- Convert the second character from the end

print

(

string.byte

(

"Lua"

,-

2

)

)

-- Convert an integer ASCII code to a character

print

(

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

print

(

"Concatenated string"

,

string1

..

string2

..

string3

)

-- String length

print

(

"String length "

,

string.len

(

string2

)

)

-- Replicate the string 2 times

repeatedString

=

string.rep

(

string2

,

2

)

print

(

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"

print

(

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

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:

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.