Page 1 of 1

I am trying to draw multipule objects but only one is being drawn

Posted: Sat Jul 06, 2019 4:37 pm
by shabbs15
So the hunger goes down by 1 every second and each time this happens a pop-up is meant to come up saying -1. I have not implemented the code for the pop-ups to be deleted yet so they all should be there. Yet, when I run my code only one pop-up is shown each time. But I can tell a new pop-up is being created as it is moving in a random location every time

Any help would be hugely appreciated

Re: I am trying to draw multipule objects but only one is being drawn

Posted: Sat Jul 06, 2019 8:52 pm
by pgimeno
This is a good example of why avoiding globals everywhere is a good idea.

Your bug is caused by the fact that 'object' is a global. This is your object:draw function:

Code: Select all

    function object:draw()
        love.graphics.print({object.color,tostring(value)}, object.x, object.y)
    end
Since 'object' is a global, the values used to draw will always be the last ones assigned to the global. As a result, the same value is drawn multiple times on the same coordinates.

To solve your immediate problem, just add 'local' in front of 'object = {}'.

Re: I am trying to draw multipule objects but only one is being drawn

Posted: Sun Jul 07, 2019 5:58 am
by sphyrth
pgimeno wrote: Sat Jul 06, 2019 8:52 pm This is a good example of why avoiding globals everywhere is a good idea.
More like "remembering local variables" is a good idea. I mean, I've stumbled several times simply because I forgot to put in local in my variables.

But yeah, what you said.

Code: Select all

local object = {}

Re: I am trying to draw multipule objects but only one is being drawn

Posted: Sun Jul 07, 2019 9:45 am
by shabbs15
thanks a lot

Re: I am trying to draw multipule objects but only one is being drawn

Posted: Sun Jul 07, 2019 9:49 am
by pgimeno
sphyrth wrote: Sun Jul 07, 2019 5:58 am More like "remembering local variables" is a good idea. I mean, I've stumbled several times simply because I forgot to put in local in my variables.
Or that, yeah :nyu: (that's why I made a globals finder: https://love2d.org/forums/viewtopic.php?f=5&t=86717)

Anyway, in the case in point, it could also have been avoided by using 'self' instead of 'object', with the additional benefit that the function could have been defined outside, so that it doesn't create one closure for every call:

Code: Select all

local function object_draw(self)
    love.graphics.print({self.color,tostring(value)}, self.x, self.y)
end

function newPopUp(x,y,value)
    local object = {}
    ...
    object.draw = object_draw
    ...
    return object
end
Of course, using both like above have been even better.