61 posts / categories / feed

Basic Lua Programming with Tables

Creating and Using Tables

In Lua, it is optimized to use Tables which in other languages they are better known as “Arrays”.

Create a Table

Special note that in Lua, unlike the general idea of accessing Arrays where the first index starts from index 0, Lua starts from 1. Hence to access the first item in the table, you will have to use table[1] instead of table[0] in general array.

local table = {"test1", "test2", "test3"}

Getting Length of the Table

In Lua, to get the length of a table, do not try to attempt table.length etc. It is simply to use the “#” followed by the table name, like so #table.


Getting the Table in Memory

Using toString to convert the name of the table to string.


Creating Associative Index in Table

There are a few ways of creating associative index, you may assign the values when creating a table, or create an empty table and add the values at a later stage.

-- Creating an associative index table
local table1 = {
    test1 = "test1",
    test2 = "test2"

-- Creating an empty table, and assigning values later
local table2 = {};
table2.test1 = "test1";
table2.test2 = "test2";

-- Displaying values like so...

Creating a Big Table

Note that it may get a little out of hand if your table is too complex, hence it is important to structure your table.

-- Overriding the whole table
local table = {
    {"hello", "world"},
    {"hehe", "haha", "wow"},
    tests = {
        t1 = "nested table",
        t2 = 120

-- to access "world"

-- to access "haha and wow"
print(table[2][2] .. " and " .. table[2][3]);

-- to access associative key through dot syntax
-- note: cannot access numeric index like print(table.1);
-- note: not possible to use print(#table.tests) to get the length of associative index, need to iterate through

Releasing Table for Garbage Collection

Similarly, when done with the table, it is better to send it for garbage collection by assigning nil to the table.

table = nil;
table1 = nil;
table2 = nil;