table访问的元方法
Window = {}
Window.prototype = {x=0,y=0,width=100,height=100}
Window.mt = {}

function Window.New(x)
setmetatable(x,Window.mt)
return x
end

Window.mt.__index = function(t,k)
return Window.prototype[k]
end

t = Window.New({})
print(t.width)

Window.mt.__newindex = function(t,n,v)
error("not exists "..n,2)
end

--t.ll = 2  会报错

Window.mt.__index = {width=888}
print(t.width)  --888

Window.mt.__newindex = {}
t.ll = 2;
print(t.ll)  --nil
print(Window.mt.__newindex.ll)  --2


__index元方法,主要table访问不存在的元素的时候,就会调用该方法,可以用来做继承,返回一些默认的值,如果__index是一个table,会自动去这个table查找那个值并返回。

__newindex元方法,主要在table对一个不存在属性进行赋值时调用的方法,如果__newindex引用的是一个table,那么会将值添加到这个table中了。


首页 我的博客
粤ICP备17103704号