I'm trying to learn Lua, so hopefully this is an easy question to answer. The following code does not work. The variable childContext leaks between all instances of classes.
--[[--
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
Looking at the Object oriented lua classes leaking I can fix my problem by changing the constructor function to:
-- 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
So my questions are:
- Is there a cleaner way to declare class variables, much like the first example, so I do not have to include it in the constructor?
- Why does the CxBR_Context.name work, but the table CxBR_Context.childContexts do not?