reference:
http://www.lua.org/manual/5.3/manual.html
__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
.
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.)
__index这个重载,主要是重载了find key的操作,这操作可以让Lua变得有点面向对象的感觉。 所谓__index,说得明确一点,如果我们有两个对象a和b,我们想让b作为a的prototype只需要:
setmetatable(a, {__index = b})
metamethod 为function
示例:
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)
执行结果:
Hello 100
metamethod 为table
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)
执行结果:
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)