Confusão de usar a notação “.” Com __index e espaço para nome em Lua
Estou confuso das duas sintaxes a seguir usando "."
Pelo que entendi,__index
é chamado quando uma chave não existe em uma tabela, mas existe em sua meta-tabela. Então, por que a tabela da lista chama__index
e depois se atribuir alist.__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 })
FazWindow.mt
basta criar uma tabela? Por que precisamosWindow = {}
como um espaço para nome aqui?
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