【问题标题】:If item in list lua如果列表中的项目 lua
【发布时间】:2020-09-30 13:29:05
【问题描述】:

所以我在 lua 中有一个类似这样的列表

hello
hello1
hello2

我想看看x 字符串是否在我的列表中。 我知道如何在 python 中做到这一点,但我完全不知道如何在 lua 中做到这一点(有点紧凑?)

在python中:

list = ["hello1", "hello2", "hello3"]

if "hello1" in list:
   print("this worked!")
else:
   print("this didn't")

【问题讨论】:

标签: lua


【解决方案1】:

你会想做这样的事情:

local list = {"Example", "Test"} -- This is the list of items
local target = "Test" -- This is what it will look for
local hasFound =  false

for key, value in pairs(list) do -- For all the values/"items" in the list, do this:
    if value == target then
        hasFound = true
    end
    -- You dont want to add an else, since otherwise only the last item would count.
end

if hasFound then -- If you dont put anything then it automatically checks that it isnt either nil nor false.
    print("Item "..target.." has been found in list!")
else
    print("Item "..target.." has not been found in list!")
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 2021-12-02
    • 2016-12-28
    • 2014-01-31
    • 2015-05-25
    • 2012-06-06
    • 1970-01-01
    相关资源
    最近更新 更多