LUA Tables as HashTables and a little bit more

Tables can be used as Hash Tables where each element is associated by a name.

local dimens = {
    height = 10,
    width = 5
}

dimens.depth = 2

You will notice above an additional element is added without having to resize the table or pre-define the element.

print( dimens.depth ) -- 2
print( dimens["depth"] ) -- 2

Advanced Collections
As well as numbers and string a table can hold functions, references to functions as well as other tables.

local products = {
    {code = "Prod1", description = "bulb" , price = 32.50, quantity = 22},
    {code = "Prod2", description = "door" , price = 10.02, quantity = 2}
}

print (products[2]["code"])  -- Prod2
print (products[2].description)   -- door
print (products[2].price)  -- 10.02
print (products[2]["quantity"])  -- 2

Tables can be mixed (Hash Table and Array)
A table can hold array and hash table structures.

local mixed = {
    "alpha",
    "beta",
    ["one"] = "uno",
    ["two"] = "dos"
}

Iterating elements

for key, value in pairs[mixed] do
    print(key, value)
end

The output from the above is:

1, alpha
2, beta
one, uno
two, dos

Tables can contain function references

local function helloWorld()
    print( "Hello World!" )
end

local myTable = {
    name = "Bob",
    func = helloWorld}

myTable.func() -- output: Hello World!

----------

local function helloWorld()
    print( "Hello World!" )
end

local myTable = { 100, 100, helloWorld, true }

myTable[3]()    -- output: Hello World!

Tables can contain actual functions

local myTable = {
    100,
    100,
    function() print( "Hello World!" ); end,
    true
}

myTable[3]    -- output: Hello World!

Leave a Reply