Lua inserting a record to a table is failing -
i have main script follows . script called script.lua (for sake of example)
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 happy?" , "yes") parentclass:addcondition(condition1) -- -- condition 2 condition2 = condition:new(nil,"are sad?" , "no") parentclass:addcondition(condition2) local l = parentclass:getconditions() print(l[2]:getquestion())
i have class called myparentclass code follows
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
and have third class , conditions follows
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
the idea in main script (script.lua) ,
- i can create new parent class.
- each parent class can have multiple conditions (aka questions).
for me, first part working. failing second part. whenever run script , 2 instances of second question. please see below snapshot more details.
ideally, have both conditions displayed ("are happy?"
, "are sad?"
) not case.
can please me out one?
take @ constructor
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
everytime call change value of condition.question , condition.answer self refers condition, not new object o!
so create 2 new tables condition1 , condition2 both don't have own .answer , .question. therefor access metatable condition after created condition2 contains: "are sad?" , "no")
if want initialize members in constructor have use o.answer , o.question.
make sure understand how metatable stuff works.
Comments
Post a Comment