我正在尝试学习 Lua,所以希望这是一个容易回答的问题。以下代码不起作用。变量 childContext 在类的所有实例之间泄漏。
--[[--
Context class.
--]]--
CxBR_Context = {}
-- Name of Context
CxBR_Context.name = "Context Name Not Set"
-- Child Context List
CxBR_Context.childContexts = {}
-- Create a new instance of a context class
function CxBR_Context:New (object)
object = object or {} -- create object if user does not provide one
setmetatable(object, self)
self.__index = self
return object
end
-- Add Child Context
function CxBR_Context:AddChildContext(context)
table.insert(self.childContexts, context)
print("Add Child Context " .. context.name .. " to " .. self.name)
end
--[[--
Context 1 class. Inherits CxBR_Context
--]]--
Context1 = CxBR_Context:New{name = "Context1"}
--[[--
Context 1A class.Inherits CxBR_Context
--]]--
Context1A = CxBR_Context:New{name = "Context1A"}
--[[--
Context 2 class.Inherits CxBR_Context
--]]--
Context2 = CxBR_Context:New{name = "Context2"}
--[[--
TEST
--]]--
context1 = Context1:New() -- Create instance of Context 1 class
print(context1.name .." has " .. table.getn(context1.childContexts) .. " children")
context2 = Context2:New() -- Create instance of Context 2 class
print(context2.name .." has " .. table.getn(context2.childContexts) .. " children")
context1A = Context1A:New() -- Create instance of Context 1A class
print(context1A.name .." has " .. table.getn(context1A.childContexts) .. " children")
context1:AddChildContext(context1A) -- Add Context 1A as child to context 1
print(context1.name .." has " .. table.getn(context1.childContexts) .. " children") -- Results Okay, has 1 child
print(context2.name .." has " .. table.getn(context2.childContexts) .. " children") -- Why does thin return 1, should be 0
查看面向对象的 lua 类泄漏,我可以通过将构造函数更改为:
-- Child Context List
-- CxBR_Context.childContexts = {}
-- Create a new instance of a context class
function CxBR_Context:New (object)
object = object or { childContexts = {} } -- create object if user does not provide one
setmetatable(object, self)
self.__index = self
return object
end
所以我的问题是:
- 有没有一种更简洁的方式来声明类变量,就像第一个示例一样,所以我不必将它包含在构造函数中?
- 为什么 CxBR_Context.name 可以工作,而表 CxBR_Context.childContexts 却不行?