Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble adding elements to a table (array in Lua)

Tags:

arrays

lua

I am attempting to create a table to serve as a small database for users:

users = {}

function create_new_user()
    print("Enter a unique user name (up to 12 letters): ")
    local name = io.read()
    if #name > 12 then 
        print ("That name is too long.")
        return create_new_user()
    elseif users[name] then
        print ("That name is already in use.")
        return create_new_user()
    else
        table.insert(users, 1, name)    
        print("Your new user name is: ", users[name])
    end
end

I understood from the manual that the line

table.insert(users, 1, name)

would insert the string value of name as an element of the users array. This is not the case-- whenever I run the script I get the following output:

Your new user name is:   nil
like image 740
ridthyself Avatar asked Aug 08 '26 12:08

ridthyself


1 Answers

You insert the element into the table, but you are trying to retrieve the value indexed by the value of name, which is not what you stored (you are using users[name] instead of users[1]). You can probably do something like this:

table.insert(users, name)
print("Your new user name is: ", name)

Note that table.insert(users, 1, name) may not do what you expect as this will prepend elements to the table. If you insert "abc" and "def" this way, then the users table will include elements {"def", "abc"} (in this particular order). To retrieve the last inserted element you can use users[1].

If you want to store values in a different order, you need to use table.insert(users, name), which will append elements to the table. To retrieve the last element you can use users[#users].

If you always want to store the added element in the first position in the table, then you can simply use users[1] = name.

like image 180
Paul Kulchenko Avatar answered Aug 11 '26 01:08

Paul Kulchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!