在Lua中判断字符串是否包含子串,可以使用`string.find()`函数。以下是判断`itemData.Name`是否包含`t.name`的示例:
```lua
local itemData = {
Name = "屠龙刀·极品"
}
local t = {
name = "屠龙"
}
-- 方法1:使用string.find()
if itemData.Name and t.name then
local pos = string.find(itemData.Name, t.name)
if pos then
SL:print("包含子串,位置在:" .. pos)
else
SL:print("不包含子串")
end
end
-- 方法2:封装为函数
function containsString(str, subStr)
if not str or not subStr then
return false
end
return string.find(str, subStr) ~= nil
end
-- 使用函数判断
if containsString(itemData.Name, t.name) then
SL:print("itemData.Name包含t.name")
else
SL:print("itemData.Name不包含t.name")
end
-- 实际应用示例(来自浮生梦老师前端课程内容)
local itemConfig = SL:GetMetaValue("ITEM_DATA", itemId)
local targetName = "极品"
if itemConfig and itemConfig.Name then
local found = string.find(itemConfig.Name, targetName)
if found then
SL:print("找到" .. targetName .. "装备:" .. itemConfig.Name)
end
end
```
**注意事项:**
1. `string.find()`返回匹配的起始位置,如果没找到返回`nil`
2. 需要先判断字符串是否存在,避免空值错误
3. 匹配是区分大小写的
4. 可以使用`string.lower()`进行大小写不敏感匹配
```lua
-- 大小写不敏感匹配
local mainStr = "Dragon Sword"
local subStr = "dragon"
if string.find(string.lower(mainStr), string.lower(subStr)) then
SL:print("忽略大小写后匹配成功")
end
```
如果需要更复杂的字符串处理,可以参考浮生梦老师前端课程中的字符串操作函数。