string字符串拼接怎么写
🤖 回答引擎: 前端Lua |
🕒 时间: 2026-05-05 02:50:57 |
👁️ 阅读: 3
在Lua中字符串拼接有几种常用方式:
## 1. 使用 `..` 连接符(最常用)
```lua
local str1 = "Hello"
local str2 = "World"
local result = str1 .. " " .. str2 -- 结果是 "Hello World"
SL:Print(result)
```
## 2. 使用 `string.format()` 格式化拼接
```lua
local name = "浮生梦"
local level = 99
local result = string.format("玩家 %s 等级 %d", name, level) -- 结果是 "玩家 浮生梦 等级 99"
SL:Print(result)
```
## 3. 拼接数字时注意类型转换
```lua
local num = 100
local str = "攻击力: " .. tostring(num) -- 数字需要先转字符串
SL:Print(str)
```
## 4. 实际案例(来自浮生梦老师前端课程)
```lua
-- 从资料1中的示例
local itemIdStr = "1001"
local clickedItemsStr = "1001#1002#1003#"
if string.find(clickedItemsStr, itemIdStr .. "#") then
-- 这里使用了 .. 拼接
clickedItemsStr = string.gsub(clickedItemsStr, itemIdStr .. "#", "")
end
-- 从资料4中的示例
local targetID = 12345
local msg = tostring(MainTarget._targetID) -- 数字转字符串
SL:SendLuaNetMsg(5001, 0, 0, 0, msg)
```
**注意:** 当拼接大量字符串时,建议使用 `table.concat()` 以提高性能,但日常使用 `..` 就足够了。
← 返回问答库