【问题标题】:How to make a function that searches through the user input for a data inside an array?如何制作一个通过用户输入搜索数组内数据的函数?
【发布时间】:2020-08-28 01:43:49
【问题描述】:

我正在学习用 Lua 编程,我正在尝试练习使用函数和数组。

这个想法是程序接受用户输入并验证所述数据是否存在于数组中,否则它应该返回它不存在。

number = {"1", "2", "3"}
function prompt(input)
    if input == number then
        return print("Yes your number is here")
    else
        return print("Nope, your number not here")
    end
end

prompt = tostring(io.read())

但是,在这种情况下,我似乎没有完全理解如何调用我的函数来使用它,我应该如何构造它?

【问题讨论】:

标签: arrays function input lua


【解决方案1】:

使用调用运算符()调用函数

函数定义:

function myFunction(text)
  print(text)
end

函数调用:

myFunction("Hello world!")

promt = tostring(io.read())promt 引用到tostring(io.read()) 的返回值,因此promt 不再引用您之前定义的函数。

你想做prompt(io.read())之类的事情。

请注意,您的代码还存在一些其他问题。例如,您尝试将表与始终为假的字符串值进行比较。您必须在循环中单独检查每个表格元素。

请做一个初学者教程并阅读 Lua 参考手册。

【讨论】:

    【解决方案2】:

    以你想要的方式调用提示函数的正确方法是这样的:

    prompt(tostring(io.read()))
    

    您正在做的是将prompt 重新声明为输入的值,而不是函数。

    另外,您检查输入值是否存在于表中的方式不正确。

    if input == number then
    

    这不适用于任何(或至少大多数)编程语言。您在这里所做的是将字符串比较 与表格。是的,您正在比较,而不是检查表是否包含字符串。基本上你是在告诉代码:我的字符串是否相当于这张表?.

    为了找出表中是否存在字符串,您需要循环表并分别比较表中的每个值。下面是一篇文章谈到了这一点:

    Search for an item in a Lua list

    您的代码如下所示:

    local number = {"1", "2", "3"}
    function prompt(input)
        for index, item in ipairs(number) do
            if input == item then
                -- If we find a match print and return
                return print("Yes your number is here")
            end
        end
    
        -- No match. We know this as the above code would have returned
        -- if a match had been found and thus never reach this part of the code.
        return print("Nope, your number not here")
    end
    
    prompt(tostring(io.read()))
    

    【讨论】:

      猜你喜欢
      • 2018-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      • 2011-12-19
      相关资源
      最近更新 更多