reference:html
http://www.lua.org/manual/5.3/manual.htmlapp
__index
: The indexing access table[key]
. This event happens when table
is not a table or when key
is not present in table
. The metamethod is looked up in table
.this
Despite the name, the metamethod for this event can be either a function or a table. If it is a function, it is called with table
and key
as arguments, and the result of the call (adjusted to one value) is the result of the operation. If it is a table, the final result is the result of indexing this table with key
. (This indexing is regular, not raw, and therefore can trigger another metamethod.)lua
__index这个重载,主要是重载了find key的操做,这操做可让Lua变得有点面向对象的感受。 所谓__index,说得明确一点,若是咱们有两个对象a和b,咱们想让b做为a的prototype只须要:spa
setmetatable(a, {__index = b})
示例:prototype
Window_Prototype = {x=0, y=0, width=100, height=100} MyWin = {title="Hello"} Window = {} Window.__index = function(table, key) return Window_Prototype[key] end setmetatable(MyWin,Window) print(MyWin.title, MyWin.width)
执行结果:code
Hello 100
Window_Prototype = {x=0, y=0, width=100, height=100} MyWin = {title="Hello"} Window = {} Window.__index = Window_Prototype setmetatable(MyWin,Window) print(MyWin.title, MyWin.width)
执行结果:htm
Hello 100
metamethod 为table简洁的书写方式:对象
Window_Prototype = {x=0, y=0, width=100, height=100} MyWin = {title="Hello"} setmetatable(MyWin, {__index = Window_Prototype}) print(MyWin.title, MyWin.width)