的笔记

随时随地编辑

Metatables

参考资料

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.

  1. "add": the + operation.
  2. "sub": the - operation. Behavior similar to the "add" operation.
  3. "mul": the * operation. Behavior similar to the "add" operation.
  4. "div": the / operation. Behavior similar to the "add" operation.
  5. "mod": the % operation. Behavior similar to the "add" operation, with the operation o1 - floor(o1/o2)*o2 as the primitive operation.
  6. "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.
  7. "concat": the .. (concatenation) operation.
  8. "len": the # operation.
  9. "eq": the == operation. The function getcomphandler defines how Lua chooses a metamethod for comparison operators. A metamethod only is selected when both
  10. objects being compared have the same type and the same metamethod for the selected operation.
  11. "lt": the < operation.
  12. "le": the <= operation.
  13. "index": The indexing access table[key].
  14. "newindex": The indexing assignment table[key] = value.
  15. "call": called when Lua calls a value.

posted on 2011-07-02 20:49 的笔记 阅读(283) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理