Insert key pairs into a Lua table

Just select Lua and try to figure out how to build the tables. I did a search and found the information on table.insert, but all the examples I found seem to suggest that I only need numeric indices, and what I want to do is add key pairs.

So, I wonder if this is really?

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

This will be done in a loop, and I will need to access the content later:

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

thanks

+7
source share
2 answers

There are two ways to create tables and populate them.

First you need to create and populate the table immediately using the table constructor. This is done as follows:

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

If you do not know what values ​​you want there in advance, you can first create a table using {} , and then fill it with the [] operator:

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

Please note that you can use the second (dotted) syntactic sugar only if the key is a string that matches the rules "identifier", that is, begins with a letter or underscore and contains only letters, numbers and underscores.

PS : Of course, you can combine two methods: create a table using the table constructor, and then fill in the rest using the [] operator:

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

It appears that this should be the answer:

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

Worked for me.

+1
source

All Articles