现在我正在使用闭包在Lua中实现OOP.下面是一个简略的例子.尝试在stronger_heal里面实现我的问题infested_mariner.
--------------------
-- '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
Run Code Online (Sandbox Code Playgroud)
如果我将我的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
Run Code Online (Sandbox Code Playgroud)
如何进行设置以便构造函数将受保护的表传递给彼此还有待练习。如果您走这条路,您可能希望有一些函数为您做这件事,这样您就没有机会每天接触受保护的表。
| 归档时间: |
|
| 查看次数: |
2015 次 |
| 最近记录: |