csdn学习笔记:lua继承、自索引

版权声明: https://blog.csdn.net/qq_28710983/article/details/82955452

Lua中类是对象,对象也是对象

对象:

所谓的对象,即属性和方法。

相C/C++一样使用类来访问属性和方法

Shape = {
    _width = 100,
    _height = 200,
   
};

-- Shape._getArea = function(self)
--     return self._width * self._height;
-- end

--只能这样定义,不然不能使用Shape:_getArea()访问参数
function Shape:_getArea()   --这样定义就可以象40行一样调用  --print(Shape:_getArea());
    return  self._width * self._height;
end

a = Shape;


--print(Shape:_getArea());
--print(Shape._getArea(Shape));
print(a:_getArea());   --这样调用就和c++类一样了

自索引

所谓的自索引,即将元表中的__index方法指向元表本身,可以省却一张额外的表

mt = {
    x = 2000,
    --__index = mt, ----在内部引用会报错
};

mt.__index = mt; ----自索引,__index引用在外部引用自己就可以使用了

t = setmetatable({},mt); 

print(t.x);

继承

这里存在一个self的问题,当访问表一个不存在键时,会调用元表__index键,把新键添加到self中去,而不是添加到元表中

-----继承
Account = {
    balance  = 0,
}


function Account:new(o)
    o = o or {};
    setmetatable(o,self);
    self.__index = self;
    return o;
end

----存款函数
function Account:deposit(v)
    self.balance = self.balance + v;   
end

----取款函数
function Account:withdraw(v)
    self.balance = self.balance - v;
end



CreditAccount = Account:new();              
CreditAccount:deposit(1000)
CreditAccount:withdraw(1000)

父类子类

-----继承
Account = {
    balance  = 0,
}


function Account:new(o)
    o = o or {};
    setmetatable(o,self);
    self.__index = self;
    return o;
end

----存款函数
function Account:deposit(v)
    self.balance = self.balance + v;   
end

----取款函数
function Account:withdraw(v)
    self.balance = self.balance - v;
end



CreditAccount = Account:new();              ----这里新类诞生了(Lua对象就是类,类就是对象)

function CreditAccount:disbalance()
    print(self.balance);
end



function CreditAccount:withdraw(v)    -----普通卡提款
    if v <= self.balance then
        self.balance = self.balance - v;   
    else
        print("no such money");
    end
end



credit = CreditAccount:new();               ----新类产生了对象


credit:deposit(1000);   ----存钱1000
credit:withdraw(999);
credit:disbalance();

信用卡提款透支

-----继承
Account = {
    balance  = 0,
}


function Account:new(o)
    o = o or {};
    setmetatable(o,self);
    self.__index = self;
    return o;
end

----存款函数
function Account:deposit(v)
    self.balance = self.balance + v;   
end

----取款函数
function Account:withdraw(v)
    self.balance = self.balance - v;
end



CreditAccount = Account:new();              ----这里新类诞生了(Lua对象就是类,类就是对象)


function CreditAccount:disbalance()
    print(self.balance);
end



function CreditAccount:getLimit()
    return self.limit;
end

function CreditAccount:withdraw(v)   -------信用卡提款
    if self.balance + self.limit >= v then
        self.balance = self.balance + self.limit - v;   
    else
        print("defit");
    end
end



credit = CreditAccount:new();               ----新类产生了对象


credit:deposit(1000);   ----存钱1000
credit:withdraw(999);
credit:disbalance();





猜你喜欢

转载自blog.csdn.net/qq_28710983/article/details/82955452