Lua 提供兩個專屬字串運算子:..(連接)與 #(長度),簡潔強大,是字串處理的核心工具。
| 運算子 | 功能 | 範例 | 結果 |
|---|---|---|---|
.. | 字串連接 | "Hello " .. "World" | "Hello World" |
# | 取得字串長度(位元組數) | #"Hello" | 5 |
a = "Hello "
b = "World"
print("Concatenation of string a with b is ", a .. b)
print("Length of b is ", #b)
print("Length of literal is ", #"Test")
Concatenation of string a with b is Hello World
Length of b is 5
Length of literal is 4
.. 會嘗試將數字轉為字串(10 .. 20 → "1020"),但表格/函數需先 tostring()。#s 回傳位元組數,非字元數。UTF-8 中文一佔 3 位元組,#"中文" == 6。table.concat(),避免 s = s .. x 產生大量中間字串導致 GC 壓力。__concat、__len 自訂表格/物件的連接與長度行為。local parts = {}
for i = 1, 10000 do
parts[i] = tostring(i)
end
local big_string = table.concat(parts, ", ") -- 單次配置記憶體,極快
print(#big_string)