Table Constructors

Table constructors are expressions that create tables. Every time a constructor is evaluated, a new table is created. A constructor can be used to create an empty table or to create a table and initialize some of its fields. The general syntax for constructors is

      tableconstructor ::= `{´ [fieldlist] `}´
      fieldlist ::= field {fieldsep field} [fieldsep]
      field ::= `[´ exp `]´ `=´ exp | Name `=´ exp | exp
      fieldsep ::= `,´ | `;´

Create an empty table.

T = {}

Create a table as an array where t[1] = 12, t[2] = 34, and t[3] = 56.

      t = { 12, 34, 56 }

Each field of the form [exp1] = exp2 adds an entry to the table with key exp1 and value exp2. The code below creates a table which is identical to t = {12,34,56}.

t = { [1] = 12, [2] = 34, [3] = 56 }

A field of the form name = exp is equivalent to ["name"] = exp. The code below creates a table where t["a"] = 12, t["b"] = 23, and t["c"] = 56. The two tables created below are equivalent.

t1 = { a = 12, b = 23, c = 56 }
t2 = { ["a"] = 12, ["b"] = 23, ["c"] = 56 }

Fields of the form exp are equivalent to [i] = exp, where i are consecutive numerical integers, starting with 1. Fields in the other formats do not affect this counting. The two tables created below are equivalent.

t1 = { 12, 34, 56 }
t2 = { [3] = 56, 12, 34 }

If the last field in the list has the form exp and the expression is a function call or a vararg expression, then all values returned by this expression enter the list consecutively (see Function Calls). To avoid this, enclose the function call or the vararg expression in parentheses (see Expressions).

function foo() return 34, 56 end
t = { 12, foo() }

Vararg function which creates a table that contains all of the arguments passed to the function. In this case the resulting table is the same as t = { 12, 34, 56 }

function maketable(...) return { ... } end
t = maketable(12,34,56)

The field list can have an optional trailing separator, as a convenience for machine-generated code. The table below is a valid table initialization because the , after the third value is ignored.

t = { 12, 34, 56, }