我有一个主脚本如下。这个脚本叫做script.lua(为了这个例子)
require "modules\\myparentclass"
require "modules\\condition"
require "modules\\helpers"
require "constants"
parentclass = MyParentClass:new()
print ("MyParentClass Type : " .. parentclass:getCode())
-- add conditions
-- condition 1
condition1 = Condition:new(nil,"Are you happy?" , "YES")
parentclass:addCondition(condition1)
-- -- condition 2
condition2 = Condition:new(nil,"Are you sad?" , "NO")
parentclass:addCondition(condition2)
local l = parentclass:getConditions()
print(l[2]:getQuestion())
我有另一个名为MyParentClass的类,其代码如下
require "constants"
require "modules\\condition"
require "modules\\helpers"
-- Meta class
MyParentClass = {code = ""}
function MyParentClass:new (o)
o = o or {}
setmetatable(o, self)
self.__index = self
self.condition = condition
self.conditions = {}
return o
end
function MyParentClass:getCode ()
return "Parent Class"
end
function MyParentClass:addCondition(condition)
print(condition)
table.insert(self.conditions,condition)
print('record inserted')
-- self.conditions = {next= self.conditions, value = condition}
end
function MyParentClass:getConditions()
return self.conditions
end
我有第三节课,条件如下
require "constants"
-- Meta class
Condition = {question="", answer=""}
function Condition:new (o, question,answer)
o = o or {}
setmetatable(o, self)
self.__index = self
self.question = question or nil
self.answer = answer or nil
return o
end
function Condition:getCode ()
return CONDITION_TYPE
end
function Condition:getQuestion()
return self.question
end
function Condition:getAnswer()
return self.answer
end
这个想法是在主脚本(script.lua)中,
答案 0 :(得分:1)
看看你的构造函数
function Condition:new (o, question,answer)
o = o or {}
setmetatable(o, self)
self.__index = self
self.question = question or nil
self.answer = answer or nil
return o
end
每当你调用它时,你将Condition.question和Condition.answer的值改为self引用Condition,而不是你的新对象o!
所以你实际做的是创建2个新表condition1和condition2,它们都没有自己的.answer和.question。因此,您可以访问他们的metatable条件,在您创建condition2之后包含:"你难过吗?" ," NO")
如果要在构造函数中初始化成员,则必须使用o.answer和o.question。
确保您了解这些可用的东西是如何运作的。