Hiện tại tôi đang sử dụng closures for implementing OOP ở Lua. Một ví dụ tóm tắt sau. Vấn đề của tôi xảy ra khi cố gắng triển khai stronger_heal
bên trong infested_mariner
.Làm thế nào để thực hiện các thành viên được bảo vệ khi sử dụng phương pháp đóng cửa cho OOP?
--------------------
-- '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
Nếu tôi đặt định nghĩa infested_mariner
của tôi trong một file .lua, nó sẽ không thể truy cập các biến tin toàn cầu, hoặc truy cập vào các biến tư nhân, được định nghĩa trong tập tin cơ sở .lua. Làm cách nào để tôi có các thành viên được bảo vệ mà chỉ infested_mariner
mới có thể truy cập và giải pháp không liên quan đến việc có tất cả các lớp dẫn xuất trong cùng một tệp với cha mẹ?
Lưu ý: Hiện tại tôi đang sử dụng getters và setters trong lớp con.