Lua 中不区分大小写的数组
我正在尝试为 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
I'm trying to program an addon for WoW (in lua). It's a chat filter based on specific words. I can't figure out how to get the array of these words to be case insensitive, so that any upper/lower case combination of the word matches the array. Any ideas would be greatly appreciated. Thanks!
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 if msg:lower():find ( word:lower() , 1 , true ) then
==>它降低了 string.find 的两个参数的大小写:因此不区分大小写。
我还使用了 string.find ,因为您可能需要“plain”选项,而 string.match 不存在该选项。
您还可以轻松返回找到的第一个单词:
Use
if msg:lower():find ( word:lower() , 1 , true ) then
==> it lower cases both of the arguments to string.find: hence case insensitivity.
Also I used string.find because you probably want the 'plain' option, which doesn't exist for string.match.
Also you can easily return on the first word found:
每次都把它扔掉,浪费时间
关于创建和 GC。
大写和小写字母。
来自字符串,因此使用 string.find 来提高速度。
逻辑上,如果你有多个匹配项,你就会发出“假”信号。自从
你只需要 1 场比赛,你不需要计算它们。刚回来
一旦你击中它,就会出现错误。节省您检查所有内容的时间
余言也。如果稍后您决定想要多个
匹配,你最好在循环中检查它并尽快返回
您已达到所需的计数。
不要使用 ipair。它比从 1 到数组长度的简单 for 循环要慢,而且 ipairs 在 Lua 5.2 中已被弃用。
<块引用>
结果是:
table every time just to thorw it away moments latter, wasting time
on both creation and GC.
both upper and lower case letters.
from string, so use string.find for speed.
logic, if you've got more than one match you signal 'false'. Since
you need only 1 match, you don't need to count them. Just return
false as soon as you hit it. Saves you time for checking all
remaining words too. If later you decide you want more than one
match, you still better check it inside loop and return as soon as
you've reached desired count.
Don't use ipairs. It's slower than simple for loop from 1 to array length and ipairs is deprecated in Lua 5.2 anyway.
Result is:
您还可以以完全透明的方式使用元表来安排它:
这样在任何情况下都可以对表进行索引。如果您向其中添加新单词,它也会自动将其小写。您甚至可以调整它以允许与图案或您想要的任何内容匹配。
You can also arrange this with metatables, in an entirely transparent way:
This way the table can be indexed in whatever case. If you add new words to it, it will automatically lower-case them too. You can even adjust it to allow matching with patterns or whatever you'd like.