发现一个很奇怪的现象,__index在表内定义无效,求解释~
看测试代码:
Test = {
__index = Test;
Foo = function(self)
print(self.x, self.y);
end;
};
--Test.__index = Test;
function Test:New()
local obj = {
x = 0;
y = 0;
};
setmetatable(obj, self);
return obj;
end
local t1 = Test:New();
local t2 = Test:New();
t1.x = 1;
t1.y = 2;
t2.x = 3;
t2.y = 4;
Test.Foo(t1);
t2:Foo();
for k, v in pairs(Test) do
print(k, type(v));
end
写一个类,我一般这么定义:
<ClassName> = {};
<ClassName>.__index = <ClassName>;
function <ClassName>:New()
local obj = {
<MemberVar List>
};
setmetatable(obj, self);
return obj;
end
哈,越来越喜欢lua了~