问题
I am writing an addon for the game World of Warcraft (WoW). It uses lua, with a library of functions specific to the game. I am checking whether a substring can be found in a string. The substring in question is given by the variable ItemType, which in this case contains the string "Two-Handed Swords"
. The string in which I am checking is given by a table entry and contains "One-Handed Axes, One-Handed Swords, Two-Handed Axes, Two-Handed Swords, Bows, Crossbows, Guns, Wands, Mail, Plate, Shields"
. The problem is that when I run the function on the item in question, it's acting as if the item doesn't match.
The full code is as follows
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")
returns { "Druid", "DRUID", 11 }
in this case.
ItemType
i.e. ItemInfo[7]
returns "Two-Handed Swords"
回答1:
-
is a magic character in Lua pattern matching. You need to escape it with a %
.
You can also use string.find
, which can be asked to do plain matching.
回答2:
Your strings contain characters with special meaning in Lua patterns, in this case the -
. You have to escape it with %
.
来源:https://stackoverflow.com/questions/32104947/why-isnt-this-string-match-consistently-working