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

时间:2011-09-06 00:13:47

标签: 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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:4)

  1. 定义函数外的关键字。否则你就是在重新创造 桌子每次都只是为了把它抛到一边,浪费时间 关于创作和GC。
  2. 将keyWords转换为匹配的模式 大写和小写字母。
  3. 您不需要捕获的数据 来自string,所以请使用string.find获取速度。
  4. 根据你的说法 逻辑,如果你有多个匹配,你发出'假'的信号。以来 你只需要一场比赛,你不需要计算它们。回来吧 你一碰到就错了。节省您检查所有时间的时间 剩下的话也是。如果以后你决定要多个 匹配,你还是最好在循环中检查它并尽快返回 你达到了预期的数量。
  5. 不要使用ipairs。从1到数组长度的循环比简单慢,并且在Lua 5.2中不推荐使用ipairs。

      

    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'))
    
  6. 结果是:

    true
    false
    false
    false
    true
    

答案 2 :(得分:2)

你也可以用metatables以完全透明的方式安排这个:

mt={__newindex=function(t,k,v)
    if type(k)~='string' then
        error'this table only takes string keys'
    else 
        rawset(t,k:lower(),v)
    end
end,
__index=function(t,k)
    if type(k)~='string' then
        error'this table only takes string keys'
    else
        return rawget(t,k:lower())
    end
end}

keywords=setmetatable({},mt)
for idx,word in pairs{"word","test","blah","here","code","woot"} do
    keywords[word]=idx;
end
for idx,word in ipairs{"Foo","HERE",'WooT'} do
    local res=keywords[word]
    if res then
         print(("%s at index %d in given array matches index %d in keywords"):format(word,idx,keywords[word] or 0))
    else
         print(word.." not found in keywords")
    end
end

这样可以在任何情况下对表进行索引。如果你向它添加新单词,它也会自动降低它们的大小写。你甚至可以调整它以允许匹配模式或任何你想要的。

相关问题