【问题标题】:Why isn't this string.match consistently working?为什么这个 string.match 不能始终如一地工作?
【发布时间】:2015-11-13 07:27:18
【问题描述】:

我正在为《魔兽世界》(WoW) 游戏编写插件。它使用 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"

【问题讨论】:

    标签: arrays regex string lua lua-patterns


    【解决方案1】:

    - 是 Lua 模式匹配中的一个神奇字符。您需要使用 % 转义它。

    你也可以使用string.find,它可以被要求做简单的匹配。

    【讨论】:

    • 该死,秒杀我:D
    • 我会在哪里逃脱它? NotUseableItemsTable 中的字符串? (我问是因为游戏返回了ItemType,我想不出任何方法来绕过它的格式。
    • 是的,您必须转义 ItemType。但是,正如@lhf 所指出的,您也可以使用 string.find:if string.find(NotUsableItemsString, ItemType, 1, true) then,其中1 表示从哪里开始的索引,true 告诉函数将第二个参数视为搜索字符串而不是搜索模式.
    • 破解了它。谢谢你们!
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多