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

我正在尝试为魔兽世界编写一个插件(使用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(string.lower(msg), string.lower(word))) then
            matchCount = matchCount + 1;
        end
    end
    if (matchCount > 1) then
            return false;
    else
        return true;
    end
end

原文链接 https://stackoverflow.com/questions/7313794

点赞
stackoverflow用户282536
stackoverflow用户282536

使用if msg:lower():find ( word:lower() , 1 , true ) then

== >它将两个参数都转换为小写字符串:因此不区分大小写。 此外,我使用了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
2011-09-06 00:55:01
stackoverflow用户513763
stackoverflow用户513763

你也可以用元表来完全透明地实现这一点:

mt={__newindex=function(t,k,v)
    if type(k)~='string' then
        error'此表只接受字符串键'
    else
        rawset(t,k:lower(),v)
    end
end,
__index=function(t,k)
    if type(k)~='string' then
        error'此表只接受字符串键'
    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 在给定的数组中的索引为 %d,与关键字中的索引 %d 匹配"):format(word,idx,keywords[word] or 0))
    else
         print(word.." 没有在关键字中找到")
    end
end

这样,表格就可以以任何大小写形式进行索引。如果您添加了新单词,它们也会自动小写。您甚至可以调整它以允许与模式或其他任何您想要的匹配。

2011-09-06 07:39:00
stackoverflow用户936986
stackoverflow用户936986
  1. 在函数外定义关键词。否则,每次都会重新创建表格,然后在片刻后将其丢弃,从而浪费创建和GC时间。
  2. 将关键词转换为适配大小写字母的模式。
  3. 您不需要从字符串中获取捕获的数据,因此可以使用string.find进行加速。
  4. 根据您的逻辑,如果匹配项多于1个,则会发出“false”信号。由于仅需要1个匹配项,因此不需要计算它们。只需在找到匹配项后立即返回false。这样可以节省检查所有剩余单词的时间。如果以后决定需要多个匹配,最好在循环内检查并在达到所需计数时立即返回。
  5. 不要使用ipairs。它比从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'))

结果是:

true
false
false
false
true
2012-04-13 10:45:01