检查表中包含项目的字符串

时间:2015-01-27 19:24:44

标签: lua lua-table

if FirstName:GetValue() == ""
or table.HasValue( Blocked, string.lower(FirstName:GetValue())) then
-- Checks if the name contains any "bad" words, or nothing was typed in.
    FirstNameCHECK = false
    text4:SetText("Bad Name")
    text4:SetColor(Color(255,0,0,255))
else
    FirstNameCHECK = true
    text4:SetText("Good Name")
    text4:SetColor(Color(0,255,0,255))
end

此代码当前检查字符串是否与表中的条目完全相同。

我如何能够更改此代码,以便检查插入的字符串(FirstName变量)是否包含表中的一个条目?

2 个答案:

答案 0 :(得分:1)

效率低下的解决方案是迭代表并在每个元素上调用string.find。对于非常大的表,这种方法可能会非常慢,因为您必须检查每个元素,但除非您处理的是非常大的数据集,否则可能会非常好。

更聪明的方法是使用由子字符串索引的嵌套表。例如,您可以拥有索引az的根表。使用单词的第一个字母为该表索引,然后返回另一个具有相同结构的表。这一个你用第二个字母索引,依此类推,直到你在你正在检查的字母上找不到更多的表格,或者你到达了单词的末尾。在后一种情况下,您可能需要在表格中添加一个唯一的条目,指示您正在查找的确切单词是否在表格中(因为没有更多的字母,您需要能够以某种方式检查)。

这种方法有几个缺点。构建表可能会占用大量内存,并且执行检查可能比较小表的简单方法慢。操纵查找表也不是那么简单(例如考虑从中删除一个单词)。所以这种结构实际上只对执行查找有用,你应该坚持使用普通表来完成其他任务。

例如,您可能希望在查找表中维护实际数据表中条目的引用列表,这些条目允许您从特定前缀字符串中获取数据表中所有匹配条目。

答案 1 :(得分:0)

在其他一些问题中为这些东西制作解决方案(适用于多维表) - Loop until find 2 specific values in a table?

function MultiTableSearch(input,value,case,index_check)
    if (input and type(input) == 'table') then
        if (type(value) == 'table' and value == input) then
            return true;
        end
        for key,object in pairs(input) do
            if (index_check) then
                if (case and type(input)=='string' and type(key)=='string') then
                    if (value:lower() == key:lower()) then -- to avoid exit the loop
                        return true;
                    end
                else
                    if (key == value) then
                        return true
                    elseif(type(object)=='table') then
                        return MultiTableSearch(object,value,case,index_check)
                    end
                end
            else
                if (case and type(value)=='string' and type(object) == 'string') then
                    if (value:lower() == object:lower()) then
                        return true;
                    end
                elseif(type(object)=='table') then
                    if (value == object) then
                        return true;
                    else
                        return MultiTableSearch(object,value,case)
                    end
                else
                    if (object == value) then
                        return true;
                    end
                end
            end
        end
    end
    return false;
end

并使用调用此

MultiTableSearch(blocked,FirstName:GetValue(),true) -- table,name,case(true to ignore case)