46

In Lua, you can create a table the following way :

local t = { 1, 2, 3, 4, 5 }

However, I want to create an associative table, I have to do it the following way :

local t = {}
t['foo'] = 1
t['bar'] = 2

The following gives an error :

local t = { 'foo' = 1, 'bar' = 2 }

Is there a way to do it similarly to my first code snippet ?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Wookai
  • 20,883
  • 16
  • 73
  • 86

3 Answers3

81

The correct way to write this is either

local t = { foo = 1, bar = 2}

Or, if the keys in your table are not legal identifiers:

local t = { ["one key"] = 1, ["another key"] = 2}
bendin
  • 9,424
  • 1
  • 39
  • 37
  • FYI, there's a similar answer here, that contains more of an explanation, and that I found easier to understand: https://stackoverflow.com/a/16288476/5505583 – Seth Sep 10 '21 at 19:22
12

i belive it works a bit better and understandable if you look at it like this

local tablename = {["key"]="value",
                   ["key1"]="value",
                   ...}

finding a result with : tablename.key=value

Tables as dictionaries

Tables can also be used to store information which is not indexed numerically, or sequentially, as with arrays. These storage types are sometimes called dictionaries, associative arrays, hashes, or mapping types. We'll use the term dictionary where an element pair has a key and a value. The key is used to set and retrieve a value associated with it. Note that just like arrays we can use the table[key] = value format to insert elements into the table. A key need not be a number, it can be a string, or for that matter, nearly any other Lua object (except for nil or 0/0). Let's construct a table with some key-value pairs in it:

> t = { apple="green", orange="orange", banana="yellow" }
> for k,v in pairs(t) do print(k,v) end
apple   green
orange  orange
banana  yellow

from : http://lua-users.org/wiki/TablesTutorial

HK boy
  • 1,398
  • 11
  • 17
  • 25
Wesker
  • 231
  • 1
  • 3
  • 10
2

To initialize associative array which has string keys matched by string values, you should use

local petFamilies = {["Bat"]="Cunning",["Bear"]="Tenacity"};

but not

local petFamilies = {["Bat"]=["Cunning"],["Bear"]=["Tenacity"]};
izogfif
  • 125
  • 1
  • 5