参考资料
Referenced Values, Metatables, and Simple Inheritance>
http://phrogz.net/lua/LearningLua_ValuesAndMetatables.html
Metatable In Lua 浅尝辄止
http://www.cnblogs.com/simonw/archive/2007/01/17/622032.html
扯淡
metatable只是一个普通的table,当你它他当做metatable来用的时候,他就成了metatable:
setmetatable( theFirstTable, theOtherTable )
如果一个table有一个metatable,碰巧的是这个metatable有一写特殊的关键字,则在使用这个table的时候,会发生一个写有趣的事情:
function gettable_event (table, key)
local h
if type(table) == "table" then
local v = rawget(table, key)
if v ~= nil then return v end
h = metatable(table).__index
if h == nil then return nil end
else
h = metatable(table).__index
if h == nil then
error("...");
end
end
if type(h) == "function" then
return h(table, key) -- call the handler
else return h[key] -- or repeat operation on it
end
也就是,你访问表,其实最终访问到表的metatable上去了。这些就是lua mirror a cplusplus class的基本原理。细节是复杂的,也很晦涩。
Metatables
15个重载方法(http://www.lua.org/manual/5.1/manual.html#2.8)
We call the keys in a metatable events and the values metamethods. In the previous example, the event is "add" and the metamethod is the function that performs the addition.
- "add": the + operation.
- "sub": the - operation. Behavior similar to the "add" operation.
- "mul": the * operation. Behavior similar to the "add" operation.
- "div": the / operation. Behavior similar to the "add" operation.
- "mod": the % operation. Behavior similar to the "add" operation, with the operation o1 - floor(o1/o2)*o2 as the primitive operation.
- "pow": the ^ (exponentiation) operation. Behavior similar to the "add" operation, with the function pow (from the C math library) as the primitive operation."unm": the unary - operation.
- "concat": the .. (concatenation) operation.
- "len": the # operation.
- "eq": the == operation. The function getcomphandler defines how Lua chooses a metamethod for comparison operators. A metamethod only is selected when both
- objects being compared have the same type and the same metamethod for the selected operation.
- "lt": the < operation.
- "le": the <= operation.
- "index": The indexing access table[key].
- "newindex": The indexing assignment table[key] = value.
- "call": called when Lua calls a value.