Difference Between Tables and Metatables in Lua

Rahul Singh picture Rahul Singh · Jun 5, 2012 · Viewed 9.6k times · Source

What is the difference between tables and metatables in Corona? What are the types of metatables? How and where can I use them? What is the main purpose of using tables and metatables?

Answer

Michal Kottman picture Michal Kottman · Jun 5, 2012

Tables in Lua are the main data type you can use to create dynamic, structured data. Other languages have arrays, lists, dictionaries (key-value storage), in Lua you only have tables. The only operations you can do with a basic table is indexing and storing a value using the tab[key] syntax, i.e.:

local tab = {}
tab['key1'] = 'Hello' -- storing a value using a string key
tab.key2 = 'World'    -- this is syntax sugar, equivalent to previous
print(tab.key1, tab['key2'])  -- indexing, the syntax is interchangable

You cannot do anything else with basic tables, for example adding them:

local v1={x=0,y=0}
local v2={x=1,y=1}
print(v1+v2)
--> stdin:1: attempt to perform arithmetic on local 'v1' (a table value)

A metatable allows you to modify the behavior of tables, to specify what should be done when tables are added, multiplied, concatenated (..), etc. A metatable is just a table, which contains functions with special keys, also called metamethods. You can assign a metatable to a table using setmetatable(). For example:

local Vector = {} -- this will be the metatable for vectors

function Vector.__add(v1, v2) -- what to do when vectors are added
    -- create a new table and assign it a Vector metatable
    return setmetatable({x=v1.x+v2.x, y=v1.y+v2.y}, Vector)
end
function Vector.__tostring(v) -- how a vector should be displayed
    -- this is used by tostring() and print()
    return '{x=' .. v.x .. ',y=' .. v.y .. '}'
end

local v1 = setmetatable({x=1, y=2}, Vector)
local v2 = setmetatable({x=3, y=4}, Vector)

-- vectors are added and the resulting vector is printed
print(v1 + v2) --> {x=4,y=6}

If you want to understand metatables better, you should definitely read the Programming in Lua chapter on metatables.