检查单词是否在lua中的数组中



我试图在数组中找到一个具有";橙色";它起作用,但当我添加else语句以显示消息";未找到匹配项";我得到了这个结果。

matches not found
x-orange-test
orange
new_orange
matches not found

我做错了什么?为什么我有这样的消息";未找到匹配项";如果";橙色";是否存在于阵列中?

逻辑是这样的:如果至少有一个元素带有单词";橙色";在数组中,只打印那些元素。如果该数组不包含具有字"0"的元素;橙色";打印一行";未找到匹配项";对不起,我是LUA的新手。我的代码。

local items = { 'apple', 'x-orange-test', 'orange', 'new_orange', 'banana' }

for key,value in pairs(items) do
if string.match(value, 'orange') then
print (value)
else
print ('matches not found')
end
end

等价于Python代码,对找到的元素的总和进行了轻微更正。它按照我需要的方式工作。但我需要弄清楚如何在LUA 中做同样的事情

#!/usr/bin/env python3
items = ['apple', 'x-orange-test', 'orange', 'new_orange', 'banana']
if any("orange" in s for s in items):
sum_orange = sum("orange" in s for s in items)
print (sum_orange)
else:
print('matches not found')

提前谢谢。

您的lua代码会为表中的每个元素打印结果,因此您将获得两倍的"未找到";消息,因为实际上有两个元素没有橙色。

您的Python代码使用了完全不同的逻辑,无法与lua代码进行比较。要修复lua代码,您可以使用以下内容:

found = false
for key,value in pairs(items) do
if string.match(value, 'orange') then
print (value)
found = true
end
end
if not found then
print ('matches not found')
end

对于第一个代码,您将遍历集合中的每个项,并检查是否"橙色";包含在项目中。因此,当你到达一个不包含单词"的项目时;橙色";,else条件为true,因此打印未找到的匹配项。我建议您从for循环中删除打印("找不到匹配项"(。而是创建一个布尔值来检查是否";橙色";已在集合中的任何项目中找到。在for循环之外,您可以检查布尔值是否为false,然后打印"matchnotfound"请参阅以下代码:

local items = { 'apple', 'x-orange-test', 'orange', 'new_orange', 'banana' }
local matchFound = false
for key,value in pairs(items) do
if string.match(value, 'orange') then
print (value)
matchFound = true
end
end
if not matchFound then
print('matches not found')

您可以像这样匹配迭代器。

-- table method extend
---@param t string[]
---@param value string
function table.find(t, value)
if type(t) ~= "table" or t[1] == nil then
error("is not a array")
return
end
for k, v in ipairs(t) do
if v == value then
return true, t[k]
end
end
return false, nil
end
local items = {
"apple",
"x-orange-test",
"orange",
"new_orange",
"banana"
}
print(table.find(items, "orange"))
--> true orange
print(table.find(items, "orange-odd"))
--> false nil

最新更新