lua

In lua why is print ("Name can't be empty") being executed instead of table[i] = io.read () in first iteration


As the tittle implies in first iteration print ("Name can't be empty") is executed instead of table[i] = io.read () in the first iteration

Here is the whole code

io.write("How many names do you want to enter? ")
maxNames = io.read("*n")

table = {}

for i = 1, maxNames, 1 do
    while true do
        io.write ("Enter names: ")
        table[i] = io.read ()

        if #table[i] == 0 or table[i] == " " then
            print ("Name can't be empty")
        else 
            break 
        end
    end
end

for k, items in pairs(table) do
    print ("Name in index " .. k .. " of table is " .. items)
end

print (table)

Solution

  • The io.read("*n") parses the number, but it does not consume the end-of-line symbol. So the next io.read() called to get the name - reads the rest of the line, which accidentally happens to be the empty line, because you've entered the number only. You can see this by entering 3 hello when asked for a number of names, and then you will see the hello being the first name read.

    As a simple workaround you can try to change maxNames = io.read("*n") to maxNames = io.read("*n", "*l"). The idea is to read the number, then read and discard the rest of the line.