我正在尝试为WoW编程一个插件(在lua中).这是一个基于特定单词的聊天过滤器.我无法弄清楚如何使这些单词的数组不区分大小写,以便该单词的任何大写/小写组合与数组匹配.任何想法将不胜感激.谢谢!
local function wordFilter(self,event,msg)
local keyWords = {"word","test","blah","here","code","woot"}
local matchCount = 0;
for _, word in ipairs(keyWords) do
if (string.match(msg, word,)) then
matchCount = matchCount + 1;
end
end
if (matchCount > 1) then
return false;
else
return true;
end
end
Run Code Online (Sandbox Code Playgroud)
使用 if msg:lower():find ( word:lower() , 1 , true ) then
==>它降低了string.find的两个参数的大小写:因此不区分大小写.我也使用了string.find,因为你可能想要'plain'选项,这对于string.match是不存在的.
您也可以轻松返回找到的第一个单词:
for _ , keyword in ipairs(keywords) do
if msg:lower():find( keyword:lower(), 1, true ) then return true end
end
return false
Run Code Online (Sandbox Code Playgroud)
不要使用 ipair。它比从 1 到数组长度的简单 for 循环要慢,而且 ipairs 在 Lua 5.2 中已被弃用。
local keyWords = {"word","test","blah","here","code","woot"}
local caselessKeyWordsPatterns = {}
local function letter_to_pattern(c)
return string.format("[%s%s]", string.lower(c), string.upper(c))
end
for idx = 1, #keyWords do
caselessKeyWordsPatterns[idx] = string.gsub(keyWords[idx], "%a", letter_to_pattern)
end
local function wordFilter(self, event, msg)
for idx = 1, #caselessKeyWordsPatterns do
if (string.find(msg, caselessKeyWordsPatterns[idx])) then
return false
end
end
return true
end
local _
print(wordFilter(_, _, 'omg wtf lol'))
print(wordFilter(_, _, 'word man'))
print(wordFilter(_, _, 'this is a tEsT'))
print(wordFilter(_, _, 'BlAh bLAH Blah'))
print(wordFilter(_, _, 'let me go'))
Run Code Online (Sandbox Code Playgroud)结果是:
true
false
false
false
true
Run Code Online (Sandbox Code Playgroud)