Meta tables

In Lua, meta tables can be used to modify the behavior of tables. Any table can be made into a meta table, and any table can have a meta table. Even meta tables can have their own meta tables. Meta tables change the behavior of tables using meta methods. These meta methods are functions with a specific name that affect how a table behaves.

First, create a table named meta. For now, this is a normal table. This table will have a function named __add. __add is a reserved function name. The __add function will take two arguments.

The left argument will be a table with a field called value, the right argument will be a number:

meta = { } -- Creates table
meta.__add = function(left, right) -- adds meta method
return left.value + right -- left is assumed to be a table.
end

Next, make a table called container. The container table will have a variable called value, with a value of 5:

container = {
value = 5
}

Try to add the number 4 to the container table; Lua will throw a syntax error. This is because you can't add a number to a table. The code that causes the error looks like the following:

result = container + 4 -- ERROR
print ("result: " .. result)

By adding a meta table to the container table, which has an __add meta method, we can make this code work. The setmetatable function is used to assign a meta table. The code to make this all work looks like this:

setmetatable(container, meta) -- Set meta table
result = container + 4 -- Works!
print ("result: " .. result)

When Lua tries to add anything to a table, it checks whether the table has a meta table. If the table does have a meta table, and that meta table has an __add meta method, it is executed for the addition. This means the following line of code:

result = container + 4

Is actually executed as:

result = meta.__add(container, 4)
Meta tables are perhaps the most powerful feature of Lua; however ,this concept can quickly become confusing. You can read more about meta tables at the following website: http://lua-users.org/wiki/MetamethodsTutorial.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.198.174