Lua:table对象、类、继承、多重继承

一、table对象

1.1 table有自己的操作

#!/usr/bin/env lua

--table Account
Account = { balance = 0 }

function Account.withdraw(v)
        Account.balance = Account.balance - v
end

--
a = Account; --Account = nil  --error
a.withdraw(100)
print (a["balance"])

withdraw()函数中使用了全局变量Account,如果Account被销毁了,a.withdraw(100)就会发生错误。

1.2 使用self

#!/usr/bin/env lua

--Account
Account = { balance = 0 }

function Account.withdraw(self, v)
        self.balance = self.balance - v
end

--
a = Account; Account = nil
a.withdraw(a, 100)
print (a["balance"])

1.3 省略self

#!/usr/bin/env lua

--Account
Account = { balance = 0 }

function Account:withdraw(v)
        self.balance = self.balance - v
end

--
a = Account
a:withdraw(100)
print (a["balance"])
1.4 运行结果

以上3段代码运行结果相同


二、继承

2.1 代码

#!/usr/bin/env lua

--parent class Account
Account = { balance = 0 }

function Account:withdraw(v)
        self.balance = self.balance - v
end

function Account:deposit(v)
        self.balance = self.balance + v
end

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

--child class SpecialAccount, inherit from Account
SpecialAccount = Account:new()

--object s
s = SpecialAccount:new({limit = 1000})

s:withdraw(100)
print (s["balance"])
print (s["limit"])

2.2 运行结果


三、多重继承

3.1 代码

#!/usr/bin/env

--parent class Account
Account = { balance = 0 }

function Account:withdraw(v)
        self.balance = self.balance - v
end

function Account:deposit(v)
        self.balance = self.balance + v
end

--parent class Named
Named = {}

function Named:getname()
        return self.name
end

function Named:setname(name)
        self.name = name
end

--multi inherit
local function search(k, plist)
        for i=1, #plist do
                local v = plist[i][k]
                if v then
                        return v
                end
        end
end

function createclass(...)
        local c = {}  --新类
        local parents = {...}

        setmetatable(c, {__index = function(t, k) return search(k, parents) end})

        function c:new(o)
                o = o or {}
                setmetatable(o, {__index = c})
                return o
        end

        return c
end

--child class NameCount, inherit from Account and Named
NamedCount = createclass(Account, Named)

--object account
account = NamedCount:new({name = "Tom"})

print(account:getname())
account:deposit(100)
print(account["balance"])

3.2 运行结果



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值