检查表是否包含lua中的值 [英] Check if Table contains a value in lua

查看:79
本文介绍了检查表是否包含lua中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来查看该值是否在数组(表)中

I am looking for a method to see if the value is in array (table)

示例表有3个条目,每个条目包含一个包含多个条目的表

The example table has 3 entries, each entry containing a table with multiple entries

说我要检查数据"中是否有苹果"

Say I am checking if 'apple' is in 'data'

  data = {
{"alpha","bravo","charlie","delta"},
{"apple","kiwi","banana","pear"},
{"carrot","brocoli","cabage","potatoe"}
}

这是我的代码,一个递归查询.问题在于函数会因为其正值下降而在某处中断

This is the code I have, a recursive query. The problem is the function breaks somewhere as it drops the positive value

local function hasValue(tbl, str)

local f = false

    for ind, val in pairs(tbl) do
    
            if type(val) == "table" then
        
                hasValue(val, str)

            else
                    if type(val) == "string" then
         
                        if string.gsub(val, '^%s*(.-)%s*$', '%1') == string.gsub(str, '^%s*(.-)%s*$', '%1') then 
                            f = true
                        end

                    end
            end
    end

return f end

在此方法或替代方法上的任何帮助将不胜感激.

Any help on this or alternative method would be greatly appreciated.

这是完整的测试文件

推荐答案

local function hasValue( tbl, str )
    local f = false
    for i = 1, #tbl do
        if type( tbl[i] ) == "table" then
            f = hasValue( tbl[i], str )  --  return value from recursion
            if f then break end  --  if it returned true, break out of loop
        elseif tbl[i] == str then
            return true
        end
    end
    return f
end

print( hasValue( data, 'apple' ) )
print( hasValue( data, 'dog' ) )

true
错误

true
false

这篇关于检查表是否包含lua中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆