Lua 程式設計中的字串連線
字串連線是指將兩個或更多字串相互組合的過程,在大多數程式語言中,這都可以透過使用賦值運算子來實現。
在 Lua 中,賦值運算子連線不起作用。
示例
考慮下面顯示的示例−
str1 = "tutorials" str2 = "point" will throw an error s = str1 + str2 print(s)
輸出
input:7: attempt to add a 'string' with a 'string'
因此,最直接的方法是使用連線關鍵字,該關鍵字表示為 .. (兩個點)
讓我們考慮一些 Lua 中連線關鍵字的示例。
示例
考慮下面顯示的示例−
str1 = "tutorials" str2 = "point" s = str1 .. str2 print(s)
輸出
tutorialspoint
示例
考慮下面顯示的示例−
message = "Hello, " .. "world!" print(message)
輸出
Hello, world!
請注意,Lua 不允許增強連線。
示例
考慮下面顯示的示例−
str1 = "tutorials" str2 = "point" str1 ..= str2 print(str1)
輸出
input:5: syntax error near '..'
還請注意,每當我們使用連線運算子時,都會在內部建立一個新的字串,並在該字串上執行連線,當我們要將多個字串連線到一個字串中時,這種方法會出現效能問題。
另一種方法是使用 table.concat 函式。
示例
考慮下面顯示的示例−
numbers = {}
for i=1,10 do
numbers[i] = i
end
message = table.concat(numbers)
print(message)輸出
12345678910
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP