Lua中的不区分大小写的数组

mca*_*der 7 arrays lua case

我正在尝试为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)

dau*_*tor 6

使用 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)


Ole*_*kov 4

  1. 在函数之外定义关键字。否则,您每次都会重新创建表,然后稍后将其丢弃,从而在创建和 GC 上浪费时间。
  2. 将关键字转换为同时匹配大写和小写字母的模式。
  3. 您不需要从字符串中捕获数据,因此请使用 string.find 来提高速度。
  4. 根据您的逻辑,如果您有多个匹配项,则表示“错误”。由于您只需要 1 场比赛,因此无需计算它们。只要你点击它就返回 false 。也可以节省您检查所有剩余单词的时间。如果稍后您决定需要多个匹配项,您最好在循环内检查它,并在达到所需计数后立即返回。
  5. 不要使用 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)