您的位置:首页 > 编程语言 > Lua

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

2015-11-25 18:25 633 查看
一、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 运行结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: