示例代码:
- Accout={balance=0}
- function Accout.withdraw(v)
- Accout.balance=Accout.balance-v
- end
- Accout.withdraw(100.00) --使用 . 调用方法
- function Accout.withdraw(self,v) --self或者this,表示方法作用的对象
- self.balance=self.balance-v
- end
- a1=Accout;Accout=nil
- a1.withdraw(a1,100.00) --对象 . 方法
- -------------------------------------------------------------------
- Account = {
- balance=0,
- withdraw = function (self, v)
- self.balance = self.balance - v
- end
- }
- function Account : deposit (v) -- :隐藏self参数
- self.balance = self.balance + v
- end
- Account.deposit(Account, 200.00)
- Account:withdraw(100.00) -- 使用 :调用方法
类:面向对象的语言中提供了类的概念,作为创建对象的模板。对象是类的实例。在Lua中每个对象都有一个 prototype(原 型),当调用不属于对象的某些操作时,会最先会到 prototype 中查找这些操作。
- Account = {
- balance=0,
- withdraw = function (self, v)
- self.balance = self.balance - v
- end
- }
- function Account:deposit (v)
- self.balance = self.balance + v
- end
- function Account:new (o)
- o = o or {} -- create object if user does not provide one
- setmetatable(o, self)
- self.__index = self
- return o
- end
- a = Account:new{balance = 0}
- a:deposit(100.00)
- ------------------------------------------------等价于
- Account.deposit(a, 100.00)
- b = Account:new()
- print(b.balance) --等价于 b.balance = b.balance + v
继承:类可以访问其他类的方法
- 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)
- if v > self.balance then error"insufficient funds" end
- self.balance = self.balance - v
- end
- SpecialAccount = Account:new() --子类继承基类的所有操作
- s = SpecialAccount:new{limit=1000.00}
- s:deposit(100.00)
- function SpecialAccount:withdraw (v) --重写父类方法
- if v - self.balance >= self:getLimit() then
- error"insufficient funds"
- end
- self.balance = self.balance - v
- end
- function SpecialAccount:getLimit ()
- return self.limit or 0
- end
- function s:getLimit ()
- return self.balance * 0.10
- end
多重继承:
- Account = { --类Account
- balance=0,
- withdraw = function (self, v)
- self.balance = self.balance - v
- end
- }
- local function search (k, plist) --在列表plist中查找k
- for i=1, table.getn(plist) do
- local v = plist[i][k]
- if v then return v end
- end
- end
- function createClass (...) --创建新类
- local c = {} --新类
- setmetatable(c, {__index = function (t, k) --搜索列表中的每一个方法
- local v = search(k, arg)
- t[k] = v -- 保存供下次访问
- return v
- end})
- c.__index = c --C作为_index metamethod的实例
- function c:new (o) --为新类定义构造
- o = o or {}
- setmetatable(o, c)
- return o
- end
- return c --返回新类
- end
- Named = {} --类
- function Named:getname () --类的getname()方法
- return self.name
- end
- function Named:setname (n) --类的setname()方法
- self.name = n
- end
- NamedAccount = createClass(Account, Named) --创建一个类同时继承Account,Named
- account = NamedAccount:new{name = "Paul"} --子类的实例
- print(account:getname())