字符串教程 |
|
字符串在参考手册的第 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