Search code examples
luainitializationlua-table

How to quickly initialise an associative table in Lua?


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 ?


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}