Lua基础:面向对象程序设计

本文深入讲解Lua中的面向对象编程,包括对象的创建、类的概念、继承、多重继承、私有性和单方法对象实现。通过示例代码展示了如何在Lua中实现类的定义、对象的实例化、方法的调用及重写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

示例代码:

  1. Accout={balance=0}             
  2.  
  3. function Accout.withdraw(v)
  4.     Accout.balance=Accout.balance-v
  5. end
  6.  
  7. Accout.withdraw(100.00)   --使用 调用方法
  8.  
  9. function Accout.withdraw(self,v)   --self或者this,表示方法作用的对象
  10.     self.balance=self.balance-v
  11. end
  12.  
  13. a1=Accout;Accout=nil
  14. a1.withdraw(a1,100.00)   --对象 . 方法
  15. -------------------------------------------------------------------
  16. Account = {
  17.     balance=0,
  18.     withdraw = function (self, v)
  19.         self.balance = self.balance - v
  20.     end
  21. }
  22. function Account deposit (v)            -- :隐藏self参数
  23.     self.balance = self.balance + v
  24. end
  25. Account.deposit(Account, 200.00)
  26. Account:withdraw(100.00)  -- 使用 调用方法

类:面向对象的语言中提供了类的概念,作为创建对象的模板。对象是类的实例。在Lua中每个对象都有一个 prototype(原                型),当调用不属于对象的某些操作时,会最先会到 prototype 中查找这些操作。

  1. Account = {
  2.  balance=0,
  3.  withdraw = function (self, v)
  4.  self.balance = self.balance - v
  5. end
  6. }
  7.  
  8. function Account:deposit (v)
  9.  self.balance = self.balance + v
  10. end
  11.  
  12. function Account:new (o)
  13.  o = o or {} -- create object if user does not provide one
  14.  setmetatable(o, self)
  15.  self.__index = self
  16. return o
  17. end
  18.  
  19. a = Account:new{balance = 0}
  20. a:deposit(100.00)
  21. ------------------------------------------------等价于
  22. Account.deposit(a, 100.00)
  23. b = Account:new()
  24. print(b.balance)  --等价于 b.balance = b.balance + v

继承:类可以访问其他类的方法

  1. Account = {balance = 0}           --基类
  2.  
  3. function Account:new (o)
  4.     o = o or {}
  5.     setmetatable(o, self)
  6.     self.__index = self
  7.    return o
  8. end
  9.  
  10. function Account:deposit (v)
  11.     self.balance = self.balance + v
  12. end
  13.  
  14. function Account:withdraw (v)
  15.    if v > self.balance then error"insufficient funds" end
  16.    self.balance = self.balance - v
  17. end
  18.  
  19. SpecialAccount = Account:new()       --子类继承基类的所有操作
  20. s = SpecialAccount:new{limit=1000.00}
  21. s:deposit(100.00)
  22.  
  23. function SpecialAccount:withdraw (v)       --重写父类方法
  24.    if v - self.balance >= self:getLimit() then
  25.        error"insufficient funds"
  26.    end
  27.     self.balance = self.balance - v
  28. end
  29.  
  30. function SpecialAccount:getLimit ()
  31.     return self.limit or 0
  32. end
  33.  
  34. function s:getLimit ()
  35.     return self.balance * 0.10
  36. end

多重继承:一个类同时继承其他几个类

  1. Account = {                                 --类Account
  2.     balance=0,
  3.     withdraw = function (self, v)
  4.     self.balance = self.balance - v
  5. end
  6. }
  7.  
  8. local function search (k, plist)  --在列表plist中查找k
  9.     for i=1, table.getn(plist) do
  10.         local v = plist[i][k]               
  11.         if v then return v end
  12.     end
  13. end
  14.  
  15. function createClass (...)       --创建新类
  16.     local c = {}                            --新类
  17.     setmetatable(c, {__index = function (t, k)      --搜索列表中的每一个方法
  18.        local v = search(k, arg)
  19.        t[k] = v                                            -- 保存供下次访问
  20.        return v
  21.     end})
  22.         c.__index = c        --C作为_index metamethod的实例
  23.   function c:new (o)        --为新类定义构造
  24.     o = o or {}
  25.     setmetatable(o, c)
  26.     return o
  27.     end
  28.   return c          --返回新类
  29. end
  30.  
  31. Named = {}   --类Named
  32.  
  33. function Named:getname ()  --类的getname()方法
  34.     return self.name
  35. end
  36.  
  37. function Named:setname (n) --类的setname()方法
  38.     self.name = n
  39. end
  40.  
  41. NamedAccount = createClass(Account, Named)     --创建一个类同时继承Account,Named
  42. account = NamedAccount:new{name = "Paul"}        --子类的实例
  43. print(account:getname())                                             

--------------------------------------------------------------------------------------------------------

私有性(privacy):Lua 中基本的面向对象设计并不提供私有性访问的机制,我们可以用不同的方式来实现他,Lua设计的基本思想 是,每个对象用两个表来表示:一个描述状态;另一个描述操作(或者叫接口)。

  1. function newAccount (initialBalance)
  2.    local self = {balance = initialBalance}    --表self描述对象内部状态(私有的)
  3.    local withdraw = function (v)         --创建闭包
  4.        self.balance = self.balance - v
  5.    end
  6.  
  7.    local deposit = function (v)
  8.        self.balance = self.balance + v
  9.    end
  10.  
  11.    local getBalance = function () return self.balance end
  12.    return {                     --返回对象
  13.        withdraw = withdraw,
  14.        deposit = deposit,
  15.        getBalance = getBalance
  16.      }
  17. end
  18.  
  19. acc1 = newAccount(100.00)
  20. acc1.withdraw(40.00)
  21. print(acc1.getBalance())
  22. --------------------------------------------------------
  23. 定义私有方法:
  24. function newAccount (initialBalance)
  25.    local self = {
  26.         balance = initialBalance,
  27.         LIM = 10000.00,
  28.    }
  29.  
  30.    local extra = function ()
  31.         if self.balance > self.LIM then
  32.             return self.balance*0.10
  33.         else
  34.             return 0
  35.         end
  36.     end
  37.  
  38.   local getBalance = function ()
  39.          return self.balance + self.extra()
  40.     end
  41. end

Single-Method 的对象实现方法:对象只有一个单一的方法

  1. function newObject (value)
  2.     return function (action, v)   --传入一个参数,根据参数执行分派方法
  3.         if action == "get" then return value
  4.         elseif action == "set" then value = v
  5.         else error("invalid action")
  6.         end
  7.     end
  8. end
  9.  
  10. d = newObject(0)
  11. print(d("get"))
  12. d("set", 10)
  13. print(d("get"))

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值