lua检测表中是否有某个值,检查表是否包含lua中的值

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

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

false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值