--__index用于访问
-- __index和__newindex都是在访问table中不存在的项时会被调用的
local prototype = {x = 0, y = 0, width = 100, height = 100}
function Window.new(o)
local mt = {__index = function(table,key) return prototype[key] end}
--o的元方法__index指向一个匿名函数
--Lua为__index元方法提供了一种更为简洁的表示方式,如:__index = prototype。该方法等价于上例中的匿名函数表示方法。相比而言,这种简洁的方法执行效率更高,但是函数的方法扩展性更强
setmetatable(o, mt)
return o
end
--下面是测试代码:
w = Window.new(Window)
print(w.width) --输出100
print(w.width1) --由于prototype变量中也不存在该字段,因此返回nil