0

I'm learning to program in Lua, and I'm trying to practice using functions and arrays.

The idea is that the program takes user input and verifies that said data exists in the array, otherwise it should return that it does not exist.

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())

However it seems that I must not have understood exactly how to call my function to use it in this case, How should I structure it?

2 Answers2

0

Functions are called using the call operator ()

Function definiton:

function myFunction(text)
  print(text)
end

Function call:

myFunction("Hello world!")

promt = tostring(io.read()) refers promt to the return value of tostring(io.read()) so promt does no longer refer to the function you've defined befor.

You want to do something like prompt(io.read()).

Please note that there are a few other issues with your code. For example you're trying to compare a table with a string value which is always false. You have to check each table element individually in a loop.

Please do a beginners tutorial and read the Lua Reference manual.

Piglet
  • 27,501
  • 3
  • 20
  • 43
0

The correct way to call the prompt function in the way you desire is as such:

prompt(tostring(io.read()))

What you are doing is redeclaring prompt to be the value of the input, rather than a function.

Also, the way you are checking if the input value exists in the table is incorrect.

if input == number then

This would not work in any (or at least the majority) of programming languages. What you are doing here is comparing a string to a table. Yes, you are comparing and not checking whether the table contains the string. Basically you are telling the code: is my string the equivalent of this table?.

In order to find out whether the string exists in the table, you would need to loop the table and compare each value in the table individually. Below is an article that speaks of this:

Search for an item in a Lua list

Here is what your code would look like:

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()))
Piglet
  • 27,501
  • 3
  • 20
  • 43
Colandus
  • 1,634
  • 13
  • 21