【发布时间】:2020-04-02 11:29:21
【问题描述】:
在 Lua 中的编程中,我找到了一个使用继承的示例。我了解它是如何通过元表__index 处理的,但是当我制作自己的示例时,其中一个要继承的项目是一个表,我意识到该表是由新创建的对象共享的:
Account = {
balance = 0,
info = {},
withdraw = function (self, v)
self.balance = self.balance - v
end,
deposit = function (self, v)
self.balance = self.balance + v
end,
add = function (self, item)
if self:check(item) then return end
table.insert(self.info, item)
end,
remove = function (self, item)
table.remove(self.info, item)
end,
check = function (self, item)
for i, v in ipairs(self.info) do
if v == item then return true end
end
end,
new = function (self, o)
o = o or {}
self.__index = self
setmetatable(o, self)
return o
end,
}
local a1 = Account:new()
local a2 = Account:new()
local a3 = Account:new()
a1:deposit(50)
a1:add("aaa")
a2:deposit(100)
a2:add("bbb")
a2:add("bbb")
print(a1.balance)
for _, v in ipairs(a1.info) do print(v) end
print(a2.balance)
for _, v in ipairs(a2.info) do print(v) end
这里info被所有对象共享:
50
aaa
bbb
100
aaa
bbb
如何使每个新对象中的信息独一无二?
编辑。解决方法是我将所有“字段”放在方法 new 中,同时将方法留在原型中,但我认为它不是很优雅:
new = function (self, o)
o = o or {}
o.balance = 0
o.info = {}
self.__index = self
setmetatable(o, self)
return o
end,
谢谢
【问题讨论】: