lua metatables中操做__index

reference:html

http://www.lua.org/manual/5.3/manual.htmlapp

__indexThe 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})

 

metamethod 爲function

示例: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

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)

執行結果: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)
相關文章
相關標籤/搜索