问题描述
我正在寻找一种方法来查看值是否在数组(表)中
示例表有3个条目,每个条目包含一个包含多个条目的表
说我要检查“数据”中是否有“苹果”
data = {
{"alpha","bravo","charlie","delta"},{"apple","kiwi","banana","pear"},{"carrot","brocoli","cabage","potatoe"}
}
这是我的代码,一个递归查询。问题在于该函数在下降正值时会在某处中断
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,'%1') then
f = true
end
end
end
end
return f end
解决方法
帮助:
- 您在
string.gsub
中使用的模式与整个字符串匹配,且不带空格。在您的示例中,您根本没有尾随空格,因此这是毫无意义的函数调用和比较。在这种情况下,if val == str then
应该直接进行字符串比较。 - 当您执行
f = true
时,该功能将一直运行,直到对所有项目进行迭代为止,因此,即使找到了某些内容,它也只会浪费您的CPU时间。您应该使用return true
,因为它找到了项目,不需要继续。
解决方案1:
- 最好的解决方案是对所有项目(集合列表)进行表查找。创建一个表
lookup = {}
,并在进行table.insert(a,b)
之前/之后进行迭代b
并将其所有项添加到查找表中。
for k,v in ipairs(b) do
lookup[v] = true
end
这会将b
中的值作为lookup
中的键,值true
只是我们拥有此键的指示。
稍后,如果您想知道是否有此物品,只需print("Has brocoli:",lookup["brocoli"])
解决方案2:
- 此解决方案更慢,但不需要使用其他表。只是hasValue的固定版本。
function hasValue(tbl,value)
for k,v in ipairs(tbl) do -- iterate table (for sequential tables only)
if v == value or (type(v) == "table" and hasValue(v,value)) then -- Compare value from the table directly with the value we are looking for,otherwise if the value is table,check its content for this value.
return true -- Found in this or nested table
end
end
return false -- Not found
end
注意:此函数不适用于非顺序数组。它将适用于您的代码。
,感谢答案@ codeflush.dev
local function hasValue(tbl,str)
local f = false
for ind,val in pairs(tbl) do
if type(val) == "table" then
f = hasValue(val,str)
else
if type(val) == "string" then
if string.gsub(val,'^%s*(.-)%s*$','%1') == string.gsub(str,'%1') then
f = true
end
end
end
end
return f end
,
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
错误