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"}
print(table[1]);

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.

print(#table);

Getting the Table in Memory

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

print(toString(table));

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...
print(table1["test1"]);
print(table1.test1);

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"
print(table[1][2]);

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

-- to access associative key through dot syntax
print(table.tests.t1);
-- 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;