我正在嘗試學習Lua,所以希望這是一個很容易回答的問題。以下代碼不起作用。變量childContext在類的所有實例之間泄漏。 Lua對象表在對象實例之間泄漏,但不是記錄
--[[--
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
望着Object oriented lua classes leaking我可以通過改變構造函數來解決我的問題:
-- 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不?
感謝您對構造函數工作原理的解釋。對於我,這說得通。不過,我對你的編輯有點困惑。爲什麼「對象或{childContext = {}}」不起作用?它似乎按預期工作。 – 2013-03-27 20:54:09
是的,它可能會讓人困惑。你有兩個地方,你可以調用New方法:'Context1 = CxBR_Context:New {name =「Context1」}' '和context1 = Context1:New()'。在第一種情況下,由於您將自己的表提供給構造函數,因此Context1仍然與CxBR_Context共享childContext。只有在第二個實例中,context1確實有它自己的childContexts表。這可能是你想要的,所以請不要理我的編輯。 – 2013-03-28 15:57:41
謝謝你解釋W.B. – 2013-03-29 04:09:00