字符串教程

lua-users home
wiki

引号

字符串在参考手册第 2.1 节中介绍 [1]。字符串可以使用单引号、双引号或双中括号定义。

> = "hello"
hello
> = 'hello'
hello
> = [[hello]]
hello

为什么要用这么多种方式来创建字符串?这允许你在一种引号中包含另一种。例如,

> = 'hello "Lua user"'
hello "Lua user"
> = "Its [[content]] hasn't got a substring."
Its [[content]] hasn't got a substring.
> = [[Let's have more "strings" please.]]
Let's have more "strings" please.

双中括号字符串还有一些其他特性,下面将讨论。

转义序列

Lua 也可以处理类 C 的转义序列。参考手册第 2.1 节有更多细节 [1]

> = "hello \"Lua user\""
hello "Lua user"
> = 'hello\nNew line\tTab'
hello
New line        Tab

使用双中括号时,不识别转义序列,所以

> = [[hello\nNew line\tTab]]

hello\nNew line\tTab

多行引号

双中括号可用于包含跨越多行的字面字符串。例如,

> = [[Multiple lines of text
>> can be enclosed in double square
>> brackets.]]
Multiple lines of text
can be enclosed in double square
brackets.

嵌套引号

双中括号允许嵌套,但它们需要在最外层的括号中插入一个或多个 = 来区分。插入多少个 = 并不重要,只要开头和结尾括号中的数量相同即可。

> = [[one [[two]] one]]        -- bad
stdin:1: nesting of [[...]] is deprecated near '['
> = [=[one [[two]] one]=]      -- ok
one [[two]] one
> = [===[one [[two]] one]===]  -- ok too
one [[two]] one
> = [=[one [ [==[ one]=]       -- ok. nothing special about the inner content.
one [ [==[ one

连接

可以使用连接运算符 ".." 将字符串连接在一起。例如,

> = "hello" .. " Lua user"
hello Lua user
> who = "Lua user"
> = "hello "..who
hello Lua user
数字也可以连接到字符串。在这种情况下,它们会被强制转换为字符串然后连接。你可以在下面阅读更多关于强制转换的内容。
> = "Green bottles: "..10
Green bottles: 10
> = type("Green bottles: "..10)
string

执行大量连接操作可能会很慢,因为每次连接都可能在内存中分配一个新字符串。以下三个示例产生相同的结果,但第一个可能慢得多

-- slow
local s = ''
for i=1,10000 do s = s .. math.random() .. ',' end
io.stdout:write(s)

-- fast
for i=1,10000 do io.stdout:write(tostring(math.random()), ',') end

-- fast, but uses more memory
local t = {}
for i=1,10000 do t[i] = tostring(math.random()) end
io.stdout:write(table.concat(t,','), ',') 

字符串库

Lua 在其标准库中提供了一系列用于处理和操作字符串的有用函数。更多细节可在 StringLibraryTutorial 中找到。下面是字符串库的一些用法示例。

> = string.byte("ABCDE", 2) -- return the ASCII value of the second character
66
> = string.char(65,66,67,68,69) -- return a string constructed from ASCII values
ABCDE
> = string.find("hello Lua user", "Lua") -- find substring "Lua"
7       9
> = string.find("hello Lua user", "l+") -- find one or more occurrences of "l"
3       4
> = string.format("%.7f", math.pi) -- format a number
3.1415927
> = string.format("%8s", "Lua") -- format a string
     Lua

强制转换

在适当的情况下,Lua 会自动将数字转换为字符串,或将字符串转换为数字。这称为强制转换

> = "This is Lua version " .. 5.1 .. " we are using."
This is Lua version 5.1 we are using.
> = "Pi = " .. math.pi
Pi = 3.1415926535898
> = "Pi = " .. 3.1415927
Pi = 3.1415927
如上所示,在强制转换期间,我们无法完全控制转换的格式。如果想按我们期望的方式将数字格式化为字符串,可以使用 string.format() 函数。例如,
> = string.format("%.3f", 5.1)
5.100
> = "Lua version " .. string.format("%.1f", 5.3)
Lua version 5.3
这是使用函数进行显式转换,而不是强制转换。你可以在 NumbersTutorial 中阅读更多关于数字强制转换的内容。
RecentChanges · preferences
编辑 · 历史
最后编辑于 2021 年 2 月 10 日上午 1:38 GMT (差异)