源码看了,但是怎么用的还是要看 lua in programming:
简单概括:元表是实现单继承的一种机制。
__index用来get;__newindex用来set;但都是子table找不到时才会找到元表,下面看个例子:
window = {}
window.prototype = {x=0, y=0, width = 100, height = 100}
window.mt = {}
function window:new(o)
o = o or {}
setmetatable(o, window.mt)
return o
end
window.mt.__index = function (table, key)
return window.prototype[key]
end
window.mt.__newindex = function (table, key)
print("u set non exsit member")
end
w = window.new{x=10, y = 20}
print(w.width)
w.ss = 10
>lua -e "io.stdout:setvbuf 'no'" "tt.lua"
100
u set non exsit member
>Exit code: 0
很简单吧,是的。