加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

在对OOP使用闭包方法时如何实现受保护的成员?

发布时间:2020-12-15 00:17:06 所属栏目:大数据 来源:网络整理
导读:现在我在Lua使用 closures for implementing OOP.下面是一个简略的例子.尝试在infested_mariner中实现strong_heal时,我的问题就出现了. ---------------------- 'mariner module':--------------------mariner = {}-- Global private variables:local idcoun
现在我在Lua使用 closures for implementing OOP.下面是一个简略的例子.尝试在infested_mariner中实现strong_heal时,我的问题就出现了.
--------------------
-- 'mariner module':
--------------------
mariner = {}

-- Global private variables:
local idcounter = 0
local defaultmaxhp = 200
local defaultshield = 10  

function mariner.new ()
   local self = {}

   -- Private variables:  
   local hp = maxhp        

   -- Public methods:

   function self.sethp (newhp)
      hp = math.min (maxhp,newhp)
   end
   function self.gethp ()
      return hp
   end
   function self.setarmorclass (value)
      armorclass = value
      updatearmor ()
   end


   return self
end

-----------------------------
-- 'infested_mariner' module:
-----------------------------

-- Polymorphism sample

infested_mariner = {}

function infested_mariner.bless (self)

   -- New methods:
   function self.strongerheal (value)
     -- how to access hp here?
     hp = hp + value*2  
   end      

   return self
end

function infested_mariner.new ()
   return infested_mariner.bless (mariner.new ())
end

如果我将我的infested_mariner定义放在另一个.lua文件中,它将无法访问全局私有变量,也无法访问基本.lua文件中定义的私有变量.我如何拥有只有infested_mariner可以访问的受保护成员,并且该解决方案不涉及将所有派生类与父文件放在同一文件中?

注意:我目前正在子类中使用getter和setter.

解决方法

在Lua中,您只能访问其范围内的局部变量.为了允许其他函数查看变量,您需要重写它,以便受保护的变量位于子类可访问的表中.

一种方法是在当前类中创建公共属性,并使用命名约定(如以下划线开头的名称)来表示受保护的东西.您可能知道这一点,但我不得不说,我认为这种方法通常比实际受保护的变量更容易实现.

如果您想要真正的受保护变量,则需要将表格与公共内容和受保护的内容分开.一种方法是更改??bless函数,以便它接收这两个表:

function infested_mariner.bless (pub,pro)
   -- New methods:
   function pub.strongerheal (value)
     pro.hp = pro.hp + value*2
   end
   return pub
end

如何设置以便构造函数将受保护的表传递给彼此是一个练习.如果你走这条路线,你可能想要为你做一些功能,这样你就不会有机会每天触摸受保护的桌子.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读