检查数组是否包含特定值

Check if array contains specific value

我有这个数组,其中有一些值 (int),我想检查用户给出的值是否等于该字符串中的值。如果是,则输出一条消息,如 "Got your string".

列表示例:

local op = {
{19},
{18},
{17}
}

if 13 == (the values from that array) then
  message
else
  other message

如何做到这一点?

你问题的tableop实际上是一个数组(table)的数组。

检查一个值是否存在于table:

local function contains(table, val)
   for i=1,#table do
      if table[i] == val then 
         return true
      end
   end
   return false
end

local table = {1, 2, 3}
if contains(table, 3) then
   print("Value found")
end

Lua 不像其他语言那样有严格的数组——它只有散列 tables。 Lua 中的表被认为是 类数组 当它们的索引是数字且密集排列时,不留间隙。以下 table 中的索引将是 1, 2, 3, 4.

local t = {'a', 'b', 'c', 'd'}

当你有一个类似数组的 table 时,你可以通过 循环 到 table 检查它是否包含某个值。您可以使用 for..in 循环和 ipairs 函数来创建通用函数。

local function has_value (tab, val)
    for index, value in ipairs(tab) do
        if value == val then
            return true
        end
    end

    return false
end

我们可以在 if 条件中使用上面的代码来得到我们的结果。

if has_value(arr, 'b') then
    print 'Yep'
else
    print 'Nope'
end

重申我上面的评论,您当前的示例代码不是数字数组 table。相反,它是一个类似数组的 table containing 类似数组的 tables,它们在每个第一个索引中都有数字。您需要修改上面的函数以使用您显示的代码,使其不那么通用。

local function has_value (tab, val)
    for index, value in ipairs(tab) do
        -- We grab the first index of our sub-table instead
        if value[1] == val then
            return true
        end
    end

    return false
end

Lua 不是一种非常庞大或复杂的语言,它的语法非常清晰。如果以上概念对你来说完全陌生,你需要花一些时间阅读真正的文献,而不仅仅是复制例子。我建议阅读 Programming in Lua 以确保您了解最基本的知识。这是第一版,针对Lua 5.1.

您还可以通过将您的值移动到索引并为其分配真实值来更有效地检查该值是否存在于您的数组中。

然后当你检查你的 table 时,你只需检查该索引上是否存在一个值,这会节省你一些时间,因为你不需要在最坏的情况下遍历整个 table案例场景...

这是我想到的例子:

local op = {
[19]=true,
[18]=true,
[17]=true
}


if op[19] == true then
  print("message")
else
  print("other message")
end