在Lua列表中搜索项目 [英] Search for an item in a Lua list
本文介绍了在Lua列表中搜索项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这样的项目列表:
If I have a list of items like this:
local items = { "apple", "orange", "pear", "banana" }
如何检查此列表中是否包含橙色"?
how do I check if "orange" is in this list?
在Python中,我可以这样做:
In Python I could do:
if "orange" in items:
# do something
Lua中是否有一个等价物?
Is there an equivalent in Lua?
推荐答案
Then you could put your list in the Set and test for membership:
local items = Set { "apple", "orange", "pear", "banana" }
if items["orange"] then
-- do something
end
或者您可以直接遍历列表:
Or you could iterate over the list directly:
local items = { "apple", "orange", "pear", "banana" }
for _,v in pairs(items) do
if v == "orange" then
-- do something
break
end
end
这篇关于在Lua列表中搜索项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文