Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
Delay in getParent() — Gideros Forum

Delay in getParent()

jimlevjimlev Member
edited August 2014 in Code snippets
Hello !
Here is another question, probably a stupid one for confirmed dev but...

here is an example :
Player = Core.class(Sprite)
 
function Player:init(name)
	self.myName = name
 
	self.myBag = Inventory.new()
	self:addChild(self.myBag)
end
 
 
Inventory = Core.class(Sprite)
 
function Inventory:init(name)
	self.items = {}
 
	--print(self:getParent().myName)	-- give error 'attempt to index a nil value'
	Timer.delayedCall(1000, function() print(self:getParent().myName) end) -- output 'John'
end
 
 
local firstPlayer = Player.new("John")
stage:addChild(firstPlayer)
I have an error in the init of the inventory class, if I try to access the parent of my player. If I delay the demand, it works.
Anything to learn here ? Did I do something the wrong way ?
thx !
My meditation plan :
SinisterSoft: “ I don't create classes that much - classes are good for making things simpler but imho for frame rate they are also death by a thousand cuts.”
Totebo: “ Best quote ever.”
🤔

Comments

  • ar2rsawseenar2rsawseen Maintainer
    Accepted Answer
    It's simple :)
    self.myBag = Inventory.new() --executes Inventory:init method
    --and only after that you add it to Player as child
    self:addChild(self.myBag)
    I usually do somekind of generate or prepare methods, for this purpose, as:
    function Inventory:prepare()
        print(self:getParent().myName)
    end
     
    function Player:init(name)
    	self.myName = name
     
    	self.myBag = Inventory.new()
    	self:addChild(self.myBag)
    	self.myBag:prepare()
    end

    Likes: jimlev

    +1 -1 (+1 / -0 )Share on Facebook
  • jimlevjimlev Member
    edited August 2014
    It's simple :)
    self.myBag = Inventory.new() --executes Inventory:init method
    --and only after that you add it to Player as child
    self:addChild(self.myBag)
    of course ! it's so evident ! I'm really surprised not to have encountered this problem before...
    for the 4547 times, thx a lot ar2rsawseen ! (I'm not really sure if there is more of my code or of yours in my game...)

    Likes: ar2rsawseen

    My meditation plan :
    SinisterSoft: “ I don't create classes that much - classes are good for making things simpler but imho for frame rate they are also death by a thousand cuts.”
    Totebo: “ Best quote ever.”
    🤔
    +1 -1 (+1 / -0 )Share on Facebook
Sign In or Register to comment.