Lua Tables Creating tables

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Creating an empty table is as simple as this:

local empty_table = {}

You can also create a table in the form of a simple array:

local numeric_table = {
    "Eve", "Jim", "Peter"
}
-- numeric_table[1] is automatically "Eve", numeric_table[2] is "Jim", etc.

Bear in mind that by default, table indexing starts at 1.

Also possible is creating a table with associative elements:

local conf_table = {
    hostname = "localhost",
    port     = 22,
    flags    = "-Wall -Wextra"
    clients  = {                -- nested table
        "Eve", "Jim", "Peter"
    }
}

The usage above is syntax sugar for what's below. The keys in this instance are of the type, string. The above syntax was added to make tables appear as records. This record-style syntax is paralleled by the syntax for indexing tables with string keys, as seen in 'basic usage' tutorial.

As explained in the remarks section, the record-style syntax doesn't work for every possible key. Additionally a key can be any value of any type, and the previous examples only covered strings and sequential numbers. In other cases you'll need to use the explicit syntax:

local unique_key = {}
local ops_table = {
    [unique_key] = "I'm unique!"
    ["^"]  = "power",
    [true] = true
}


Got any Lua Question?