Search code examples
dictionaryluakey-valuelua-table

Storing Key-Value and Value-Key dictionaries in a single table


Would this be okay for example :

table = { "Mark", "John", "Paul", "Matt", "Chris", ...}

and then

for k,v in pairs(table) do table[v] = k end

Or should I create two separate tables, one for each pair? Which one is better style?


Solution

  • For a list-like table where the keys are integers and the values are something else like yours, using a single table is a good idea, especially with a bit of meta-magic on it (see this answer).

    That being said, in that case, you should use ipairs to iterate it, not pairs.

    For map-like table like this, however, using two tables is better:

    my_table = {
      foo = "bar",
      spam = "eggs",
      chunky = "bacon",
    }
    

    (because imagine what would happen if you had this...)

    my_table = {
      foo = "bar",
      bar = "baz",
    }