我对使用“。”的以下两种语法感到困惑。
据我了解,
__index
当键不存在于表中但存在于其元表中时调用。那么为什么列表表调用__index
然后将自身分配给list.__index
?list = {} list.__index = list setmetatable(list, { __call = function(_, ...) local t = setmetatable({length = 0}, list) for _, v in ipairs{...} do t:push(v) end return t end }) function list:push(t) if self.last then self.last._next = t t._prev = self.last self.last = t else self.first = t self.last = t end self.length = self.length + 1 end . . . local l = list({ 2 }, {3}, {4}, { 5 })
是否
Window.mt
只是创建一个表?为什么我们需要Window = {}
在这里作为命名空间?Window = {} -- create a namespace Window.mt = {} -- create a metatable Window.prototype = {x=0, y=0, width=100, height=100, } function Window.new (o) setmetatable(o, Window.mt) return o end Window.mt.__index = function (table, key) return Window.prototype[key] end w = Window.new{x=10, y=20} print(w.width) --> 100