检查数组是否包含特定值 [英] Check if array contains specific value

查看:96
本文介绍了检查数组是否包含特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this array, with some values (int) and I want to check if a value given by the user is equal to a value in that string. If it is, output a message like "Got your string".

列表示例:

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

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

这怎么办?

推荐答案

Lua没有像其他语言一样严格的数组-它只有哈希表.当Lua中的表的索引为数字且密集排列时,它们之间被视为类数组,不留任何空白.下表中的索引为 1、2、3、4 .

Lua doesn't have strict arrays like other languages - it only has hash tables. Tables in Lua are considered array-like when their indices are numerical and densely packed, leaving no gaps. The indices in the following table would be 1, 2, 3, 4.

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

当您有一个类似数组的表时,可以通过遍历表的循环来检查它是否包含某个值.您可以使用 for..in 循环和

When you have an array-like table, you can check if it contains a certain value by looping through the table. You can use a for..in loop, and the ipairs function to create a generic function.

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 条件中使用以上内容来获取结果.

We can use the above in an if conditional to get our result.

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

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

To reiterate my comment above, your current example code is not an array-like table of numbers. Instead it is an array-like table containing array-like tables, who have numbers in each of their first indices. You'd need to modify the function above to work with your shown code, making it less generic.

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不是很大或复杂的语言,其语法非常清晰.如果上述概念对您完全陌生,则您需要花一些时间阅读真实的文献,而不仅仅是复制示例.我建议阅读在Lua中编程,以确保您了解基本知识.这是第一版,针对Lua 5.1.

Lua is not a very large or complex language, and its syntax is very clearcut. If the above concepts are totally alien to you, you'll need to spend some time reading real literature, not just copying examples. I would advise reading Programming in Lua to make sure you understand the very basics. This is the first edition, aimed at Lua 5.1.

这篇关于检查数组是否包含特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆