Question

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 ?

Was it helpful?

Solution

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}

OTHER TIPS

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

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"]};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top