[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Different behavior when __index is a table or a function
- From: Andre Arpin <arpin@...>
- Date: Tue, 21 Oct 2014 17:11:22 +0000 (UTC)
This post is long so I remove all quotes
Note: the unexpected value of self when o.baz is invoked.
_________________________CODE
require 'dump'
local metainstance = {
__index = {
foo = function(self) print(self, 'foo self') return self.v end,
},
}
setmetatable(metainstance.__index, {
__index = {
bar = function(self) print(self, 'bar self') return self.v
end,
},
})
setmetatable(getmetatable(metainstance.__index).__index, {
__index = function(self, key)
print(self, key, "self, key")
dump(self, 'self')
for k,v in pairs(self) do
print(k, v, 'k,v')
end
if key == "baz" then
print(type(self), (self).v)
return rawget(self,'v')
end
end,
})
local class = {
new = function(v) local t = {v=v} setmetatable(t, metainstance)
return t end,
}
local o = class.new(5)
print(o.v, 'o.v')
dump (o, 'o')
local oo = o
print(oo.v, 'oo.v')
dump(oo, 'oo')
print(rawget(o,'v'), "rawget(o,'v')")
print(rawget(oo,'v'), "rawget(oo,'v')")
print( o:foo(), "o:foo()" )
print( o:bar(), "o:bar()" )
print( o:baz(), "o:baz()" )
_____________________________________ OUTPUT
5 o.v
o = { -- table: 039D0230 ________AS EXPECTED
v = 5;
Metatable = ref "table: 039CFB00"; {metainstance!?!}
__index = { -- table: 039CFE70
foo = function: 039DC3D8;
Metatable = ref "table: 039D0190"; {??????(4)}
__index = { -- table: 039D0208
bar = function: 039DC438;
Metatable = ref "table: 039D0168"; {??????(6)}
__index = function: 039DC478;
};
};
};
5 oo.v
oo = { -- table: 039D0230 ________AS EXPECTED
v = 5;
Metatable = ref "table: 039CFB00"; {metainstance!?!}
__index = { -- table: 039CFE70
foo = function: 039DC3D8;
Metatable = ref "table: 039D0190"; {??????(4)}
__index = { -- table: 039D0208
bar = function: 039DC438;
Metatable = ref "table: 039D0168"; {??????(6)}
__index = function: 039DC478;
};
};
};
5 rawget(o,'v')________AS EXPECTED
5 rawget(oo,'v')________AS EXPECTED
table: 039D0230 foo self________AS EXPECTED
5 o:foo()
table: 039D0230 bar self________AS EXPECTED
5 o:bar()
table: 039D0208 baz self, key _________UNEXPECTED
self = { -- table: 039D0208
bar = function: 039DC438;
Metatable = ref "table: 039D0168"; {??????(3)}
__index = function: 039DC478;
};
bar function: 039DC438 k,v
table: 039D0208 v self, key
self = { -- table: 039D0208
bar = function: 039DC438;
Metatable = ref "table: 039D0168"; {??????(4)}
__index = function: 039DC478;
};
bar function: 039DC438 k,v
table nil
Lua: Error while running chunk
E:\lua\t.lua:46: attempt to call method 'baz' (a nil value)
stack traceback:
E:\lua\t.lua:46: in main chunk
Lua: Error while running chunk
good luck
Andre