Search code examples
lua

Inserting Key Pairs into Lua table


Just picking upon Lua and trying to figure out how to construct tables. I have done a search and found information on table.insert but all the examples I have found seem to assume I only want numeric indices while what I want to do is add key pairs.

So, I wonder if this is valid?

    my_table = {}
    my_table.insert(key = "Table Key", val = "Table Value")

This would be done in a loop and I need to be able to access the contents later in:

    for k, v in pairs(my_table) do
        ...
    end

Thanks


Solution

  • There are essentially two ways to create tables and fill them with data.

    First is to create and fill the table at once using a table constructor. This is done like follows:

    tab = {
        keyone = "first value",      -- this will be available as tab.keyone or tab["keyone"]
        ["keytwo"] = "second value", -- this uses the full syntax
    }
    

    When you do not know what values you want there beforehand, you can first create the table using {} and then fill it using the [] operator:

    tab = {}
    tab["somekey"] = "some value" -- these two lines ...
    tab.somekey = "some value"    -- ... are equivalent
    

    Note that you can use the second (dot) syntax sugar only if the key is a string respecting the "identifier" rules - i.e. starts with a letter or underscore and contains only letters, numbers and underscore.

    P.S.: Of course you can combine the two ways: create a table with the table constructor and then fill the rest using the [] operator:

    tab = { type = 'list' }
    tab.key1 = 'value one'
    tab['key2'] = 'value two'