現在、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
定義を別の .lua ファイルに配置infested_mariner
すると、グローバル プライベート変数にアクセスしたり、ベース .lua ファイルで定義されたプライベート変数にアクセスしたりできなくなります。アクセスのみできる保護されたメンバーを作成するにはどうすればよいですか?infested_mariner
また、解決策には、すべての派生クラスを親と同じファイルに含める必要はありません。
注:現在、子クラスでゲッターとセッターを使用しています。