开发者

How do metatables work and what are they used for?

I have this one question, about Lua metatables. I he开发者_运维百科ard and looked them up, but I don't understand how to use them and for what.


metatables are functions that are called under certain conditions. Take the metatable index "__newindex" (two underscores), when you assign a function to this, that function will be called when ever you add a new index to a table, like;

table['wut'] = 'lol';

this is an example of a custom metatable using '__newindex'.

ATable = {}
setmetatable(ATable, {__newindex = function(t,k,v)
    print("Attention! Index \"" .. k .. "\" now contains the value \'" .. v .. "\' in " .. tostring(t));
end});

ATable["Hey"]="Dog";

the output:

Attention! Index "Hey" now contains the value 'Dog' in table: 0022B000

metatables can also be used to describe how Tables should interact with other Tables, and different values.

This is a list of all the possible metatable indexes you can use

* __index(object, key) -- Index access "table[key]".
* __newindex(object, key, value) -- Index assignment "table[key] = value".
* __call(object, arg) -- called when Lua calls the object. arg is the argument passed.
* __len(object) -- The # length of operator.
* __concat(object1, object2) -- The .. concatination operator.
* __eq(object1, object2) -- The == equal to operator.
* __lt(object1, object2) -- The < less than operator.
* __le(object1, object2) -- The <= less than or equal to operator.
* __unm(object) -- The unary - operator.
* __add(object1, object2) -- The + addition operator.
* __sub(object1, object2) -- The - subtraction operator. Acts similar to __add.
* __mul(object1, object2) -- The * mulitplication operator. Acts similar to __add.
* __div(object1, object2) -- The / division operator. Acts similar to __add.
* __mod(object1, object2) -- The % modulus operator. Acts similar to __add.
* __tostring(object) -- Not a proper metamethod. Will return whatever you want it to return.
* __metatable -- if present, locks the metatable so getmetatable will return this instead of the metatable and setmetatable will error. 

I hope this clears things up, if you need a few more examples, click here.


They allow tables to be treated like other types such as string, functions, numbers etc.


For a high level, entertaining read on the prototype pattern check out http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html. This may help you with the 'what'.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜