← Back to Lua Course | Chapter 4: Tables | Lesson 1 of 7

Creating tables

A table is a container that stores values under keys, and it is the only data structure Lua has.

In this page:

  1. Creating tables

Creating tables

Tables are created with curly braces and can hold any value except nil as a key. The same table can mix positional items and named fields. Tables are objects, so assigning a table to another variable shares it instead of copying it.

Note: Because tables are Lua's only structure, arrays, records, sets and modules are all just tables.

Example: Creating tables

lua
local t = {10, 20, name = "box", [3.5] = "float key"}
print(t[1], t[2], t.name, t[3.5])
print(t.missing)
local alias = t
alias.name = "renamed"
print(t.name)
print(type(t), #{})

-- Output:
-- 10	20	box	float key
-- nil
-- renamed
-- table	0
Common Mistakes
  1. Expecting a table variable to hold a copy when assigned
  2. Using nil as a key
  3. Confusing the constructor {} with a block
Chapter Summary
  • Tables are made with {}
  • Any value except nil can be a key
  • One table can mix arrays and fields
  • Assignment copies the reference

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.