字串教學

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 在它的標準函式庫中提供了一系列處理字串的有用函式。可以在 字串函式庫教學 中找到更多詳細資訊。以下是使用字串函式庫的一些範例。

> = 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
這是使用函式來轉換數字的明確轉換,而不是強制轉換。可以在 數字教學 中閱讀更多關於數字強制轉換的內容。
最近變更 · 喜好設定
編輯 · 歷程記錄
最後編輯於格林威治時間 2021 年 2 月 10 日上午 7:38 (diff)