Verwechslung der Verwendung der "." - Notation mit __index und Namespace in Lua
Ich bin verwirrt von den folgenden zwei Syntaxen mit "."
Von dem, was ich verstehe,__index
wird aufgerufen, wenn ein Schlüssel nicht in einer Tabelle, sondern in seiner Metatabelle vorhanden ist. Warum ruft die Listentabelle @ au__index
und ordnen sich dann @ 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 })
TutWindow.mt
einfach eine tabelle erstellen? Warum brauchen wirWindow = {}
als Namespace hier?
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