为什么这个string.match一直在工作?

时间:2015-08-19 20:21:27

标签: arrays regex string lua lua-patterns

我正在为魔兽世界(魔兽世界)编写一个插件。它使用lua,具有特定于游戏的函数库。我正在检查是否可以在字符串中找到子字符串。有问题的子字符串由变量ItemType给出,在这种情况下包含字符串"Two-Handed Swords"。我正在检查的字符串由表条目给出,包含"One-Handed Axes, One-Handed Swords, Two-Handed Axes, Two-Handed Swords, Bows, Crossbows, Guns, Wands, Mail, Plate, Shields"。问题是,当我对相关项目运行该功能时,它的行为就好像该项目不匹配。

完整代码如下

local NotUsableItemsTable = {
    "Wands",
    "Daggers, Fist Weapons, Staves, Bows, Crossbows, Guns, Wands",
    "One-Handed Maces, Two-Handed Maces, Wands, Plate, Shields",
    "Polearms, Staves, Two-Handed Axes, Two-Handed Maces, Two-Handed Swords, Wands, Mail, Plate, Shields",
    "Fist Weapons, One-Handed Axes, One-Handed Swords, Polearms, Two-Handed Axes, Two-Handed Maces, Two-Handed Swords, Bows, Crossbows, Guns, Leather, Mail, Plate, Shields",
    "Daggers, Fist Weapons, Staves, Bows, Crossbows, Guns, Wands, Shields",
    "One-Handed Swords, Polearms, Two-Handed Swords, Bows, Crossbows, Guns, Wands, Plate",
    "Fist Weapons, One-Handed Axes, One-Handed Maces, Polearms, Two-Handed Axes, Two-Handed Maces, Two-Handed Swords, Bows, Crossbows, Guns, Leather, Mail, Plate, Shields",
    "Fist Weapons, One-Handed Axes, One-Handed Maces, Polearms, Two-Handed Axes, Two-Handed Maces, Two-Handed Swords, Bows Crossbows, Guns, Leather, Mail, Plate, Shields",
    "Placeholder String: There is no class corresponding to index 10.",
    "One-Handed Axes, One-Handed Swords, Two-Handed Axes, Two-Handed Swords, Bows, Crossbows, Guns, Wands, Mail, Plate, Shields"
}

function IsItemUseableByPlayer(itemID)
    if itemID == nil then return nil end
    local ClassInfo = {UnitClass("player")}
    local NotUsableItemsString = NotUsableItemsTable[ClassInfo[3]]
    local ItemInfo = {GetItemInfo(itemID)}
    local ItemType = ItemInfo[7]
    if string.match(NotUsableItemsString, ItemType) then
        return true
    else
        return false
    end
end
在这种情况下,

UnitClass("player")会返回{ "Druid", "DRUID", 11 }ItemTypeItemInfo[7]返回"Two-Handed Swords"

2 个答案:

答案 0 :(得分:4)

-是Lua模式匹配中的神奇角色。您需要使用%转义它。

您也可以使用string.find,可以要求它进行简单匹配。

答案 1 :(得分:0)

您的字符串包含Lua模式中具有特殊含义的字符,在本例中为-。你必须用%来逃避它。