Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting Key Pairs into Lua table

Tags:

lua

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

like image 687
Dayo Avatar asked Oct 28 '11 19:10

Dayo


People also ask

How do I add a key-value pair to a table in Lua?

You can also add key/value associations right inside the {} syntax: > t = {["foo"] = "bar", [123] = 456} > = t. foo bar > = t[123] 456. There is also a syntax shortcut for string keys in {}, as long as the string conforms to the same rules as the .

What is table insert in Lua?

The table.insert function inserts an element in a given position of an array, moving up other elements to open space. Moreover, insert increments the size of the array (using setn ). For instance, if a is the array {10, 20, 30} , after the call table.insert(a, 1, 15) a will be {15, 10, 20, 30} .

How does Lua tables work?

Lua uses a constructor expression {} to create an empty table. It is to be known that there is no fixed relationship between a variable that holds reference of table and the table itself. When we have a table a with set of elements and if we assign it to b, both a and b refer to the same memory.


2 Answers

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'
like image 194
Michal Kottman Avatar answered Sep 21 '22 15:09

Michal Kottman


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.

like image 27
Dayo Avatar answered Sep 18 '22 15:09

Dayo