Search code examples
lualua-table

How to make table from io.read in lua


I want to make a Table in lua with io.read, This is my code:

local members = {}

io.write("How many members you wanna add? ")
local memberNum = io.read("n")

print("Add new member: ")
for i = 1, memberNum do
    local newMember = io.read("*l")
    if i == 1 then
        members[1] = newMember
    else
        table.insert(members, i, newMember)
    end
end


for i = 1, #members do
    print(i, ": ", members[i])
end

I expect to result be:

members = { "Amir", "Hamid", "Bahar", "Emad", "Maryam"}

but program only accept 4 input from me and insert first input as a nil value and give me this result:

members = {"", "Amir", "Hamid", "Bahar", "Emad"}

What is the problem? Help me pls


Solution

  • Because there's a newline behind the number it reads that the first time you do io.read("*l"). The io.read("n") only takes the number without the newline. You could make this the input to make it work

    5Amir
    Hamid
    Bahar
    Emad
    Maryam
    

    or simply do an extra io.read("*l") right after the local memberNum = io.read("n")