setmetatable

When you create a new table, Lua does not give it a meta table. That is, by default a table will have a nil value for its meta table. You can assign a meta table to a table using the setmetatable method. This method takes two arguments, both are tables. The first argument is the target table, the second argument is the new meta table.

You can of course set any table to be a meta table of any other table. You can even self-assign a meta table, like the following:

container = {
value = 5,
__add = function(l, r)
return l.value + r.value
end
}

setmetatable(container, container)
result = container + container
print ("result: " .. result)

In this example, the container table has an __add method. Setting the container table to be its own meta table makes the following statement:

result = container + container

Execute as if it were actually written like this:

result = container.__add(container.value, container.value)
..................Content has been hidden....................

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