How to quickly initialise an associative table in Lua?

Wookai picture Wookai · Feb 4, 2009 · Viewed 26.9k times · Source

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 ?

Answer

bendin picture bendin · Feb 4, 2009

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}