关于 setmetable 和index的理解的博文
http://blog.csdn.net/wisdom605768292/article/details/36662033
总结:
**1.在表中查找,如果找到,返回该元素,找不到则继续
2.判断该表是否有元表,如果没有元表,返回nil,有元表则继续
3.判断元表有没有__index方法,如果__index方法为nil,则返回nil;如果__index方法是一个表,则重复1、2、3;如果__index方法是一个函数,则返回该函数的返回值**
local Account = { balance = 10,count = 100}
function Account:new( tab)
print(" [new] tab : ",tab)
print(" [new] self : ",self)
print(" [new] Account: ",Account)
setmetatable(tab,self)
self.__index = self
return tab
end
function Account:add(v)
print(" [add] self : ",self)
self.count = self.count + v
print(" count = " .. self.count)
end
local t = Account:new({ count = 30})
t:add(10)
local s = Account:new({ ss= 3})
s:add(30)
print(Account.count)
print(s.count)
基类 是account类, t类和s类分别继承
new操作:
基类有count数据
t类赋初始值 来初始化,而s类采用基类的默认初始化
看似是继承实际上也可以理解为将Account实例类 具体化为t和s两个不同的对象类型。
如下c++代码
class Account
{
public:
Account()
{ count =0;}
Account(int count)
{ this->count = count;}
public:
int count ;
int balance;
}
Account t = new account(30);
Account s = new Account();
且t和s两个对象的数据是不共享的
add方法:
在lua中的t和s中找不到add,然后找account里面的add
但是self还是t和s本身不是Account,因为是通过
t:add 和s:add调用的
通过上段的lua代码的结果也可以印证
[new] tab : table: 009E9440
[new] self : table: 009E9210
[new] Account: table: 009E9210
[add] self : table: 009E9440
count = 40
[new] tab : table: 009E9198
[new] self : table: 009E9210
[new] Account: table: 009E9210
[add] self : table: 009E9198
count = 130
100
130
[Finished in 0.2s]