Inserting Key Pairs into Lua table

Appears this should be the answer:

my_table = {}
Key = "Table Key"
-- my_table.Key = "Table Value"
my_table[Key] = "Table Value"

Did the job for me.


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'

Tags:

Lua