【发布时间】:2013-09-18 01:51:55
【问题描述】:
现在我在 Lua 中使用closures for implementing OOP。下面是一个精简的例子。我的问题是在尝试在 infested_mariner 中实现 stronger_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。
【问题讨论】: