检查数组是否包含特定值

Eth*_*tin 14 lua lua-table

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

列表示例:

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

if 13 == (the values from that array) then
  message
else
  other message
Run Code Online (Sandbox Code Playgroud)

如何才能做到这一点?

Oka*_*Oka 24

Lua没有像其他语言一样严格的数组 - 它只有哈希表.Lua中的表格被认为是数组类似的,因为它们的索引是数字且密集的,没有间隙.下表中的指数是1, 2, 3, 4.

local t = {'a', 'b', 'c', 'd'}
Run Code Online (Sandbox Code Playgroud)

当你有一个类似数组的表时,你可以通过循环遍历表来检查它是否包含某个值.您可以使用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
Run Code Online (Sandbox Code Playgroud)

我们可以在if条件中使用上面的内容来得到我们的结果.

if has_value(arr, 'b') then
    print 'Yep'
else
    print 'Nope'
end
Run Code Online (Sandbox Code Playgroud)

重申上面的评论,您当前的示例代码不是类似数组的数组表.相反,它是一个类似于数组的表,包含类似数组的表,它们的每个第一个索引都有数字.您需要修改上面的函数以使用您显示的代码,使其不那么通用.

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
Run Code Online (Sandbox Code Playgroud)

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


小智 8

您还可以通过将值移动到索引并为它们分配真值来检查数组中的值是否更有效.

然后,当您检查表时,只需检查该索引上是否存在值,这将节省您一些时间,因为在最坏的情况下您不需要遍历整个表...

这是我想到的例子:

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


if op[19] == true then
  print("message")
else
  print("other message")
end
Run Code Online (Sandbox Code Playgroud)

  • 不需要`op[19] == true`。那可以只是`op[19]` (2认同)

Die*_*ino 5

op您的问题的表实际上是一个数组的数组(表)。

要检查表中是否存在值:

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
Run Code Online (Sandbox Code Playgroud)

  • 仅当表是*序列*时才有效,在本例中就是如此。如果可能不是,请使用“for k,v inpairs(table) do if k == val then return true end return false”之类的内容 (2认同)