```lua
-- 将字符串 "1#100" 拆分为两个数字
local str = "1#100"
local parts = {}
-- 使用字符串查找函数找到分隔符位置
local pos = string.find(str, "#")
if pos then
-- 获取分隔符前的部分
local part1 = string.sub(str, 1, pos - 1)
-- 获取分隔符后的部分
local part2 = string.sub(str, pos + 1)
-- 转换为数字
local num1 = tonumber(part1)
local num2 = tonumber(part2)
-- 存储到表中
parts[1] = num1
parts[2] = num2
-- 打印结果
SL:Print("拆解结果:")
SL:Print("第一部分:", num1)
SL:Print("第二部分:", num2)
else
SL:Print("字符串中没有找到分隔符 #")
end
-- 也可以使用字符串分割函数
local function splitString(input, delimiter)
local result = {}
for match in string.gmatch(input, "[^" .. delimiter .. "]+") do
table.insert(result, tonumber(match) or match)
end
return result
end
-- 使用分割函数
local splitResult = splitString(str, "#")
SL:Print("使用分割函数:")
for i, v in ipairs(splitResult) do
SL:Print("第" .. i .. "部分:", v)
end
```
**函数说明:**
- `string.find(str, pattern)`: 在字符串中查找模式,返回匹配位置
- `string.sub(str, start, end)`: 截取字符串的子串
- `tonumber(value)`: 将值转换为数字
- `string.gmatch(str, pattern)`: 返回一个迭代器,用于遍历字符串中所有匹配模式的部分
**注意:**
- `string.find` 如果找到分隔符,返回分隔符的位置
- `string.sub` 可以截取指定范围的字符串
- 分割后的字符串需要转换为数字时使用 `tonumber`
- 如果字符串格式固定,可以直接使用硬编码方式拆分
**扩展用法:**
```lua
-- 处理多个分隔符的情况
local complexStr = "10#20#30#40"
local complexParts = splitString(complexStr, "#")
for i, v in ipairs(complexParts) do
SL:Print("值" .. i .. ":", v)
end
```
这样就能将 "1#100" 拆分为数字 1 和 100 了。