Page 1 of 1

Missing a function in love to check object:isReleased() or something like that

Posted: Wed Apr 14, 2021 9:03 am
by gcmartijn
Hi,

I'm creating and remove various objects on the fly and sometimes i'm in a situation that a draw loop is using an object that don't exist anymore.
I can fix this by refactoring some code, but maybe I can check if a object has been released (but don't know how).

Basic example code:

Code: Select all

local function drawCanvas1()
    love.graphics.clear()
    love.graphics.setColor(1, 0, 0)
    love.graphics.rectangle("fill", 0, 0, 100, 100)
end

function love.load()
    canvas1 = love.graphics.newCanvas()

    -- release it for this example
    canvas1:release()

    print(canvas1) -- Canvas: NULL -- why not nil ?
    print(canvas1.Canvas) -- nil ^ above looks like a table, but I don't get the NULL
    print(canvas1:type()) -- Canvas ! , its still a Canvas
    
    if canvas1 == nil then -- I want to check if a resource is released
        return
    end

    -- now it will give a error here
    canvas1:renderTo(drawCanvas1)
end
Thanks,

GCMartijn

Re: Missing a function in love to check object:isReleased() or something like that

Posted: Wed Apr 14, 2021 9:46 am
by grump

Code: Select all

canvas1:release()
canvas1 = nil

Re: Missing a function in love to check object:isReleased() or something like that

Posted: Wed Apr 14, 2021 10:34 am
by gcmartijn
Oke, I have to check why I din't do it this way at the moment.

Re: Missing a function in love to check object:isReleased() or something like that

Posted: Wed Apr 14, 2021 2:47 pm
by grump
Keeping released objects around is dangerous, as you've seen here. If you have to call :release() for some reason (it's usually not required, except for some edge cases whose details I can't recall), always set the object to nil immediately afterwards. If you don't really need to call :release(), then just don't do it. The garbage collector should take care of it.

Re: Missing a function in love to check object:isReleased() or something like that

Posted: Wed Apr 14, 2021 4:39 pm
by gcmartijn
Found the problem, I did forget the nil in a function

Code: Select all

---
    self.canvas:release()
    self.canvas = nil
---
I keep using the release() function to nicely cleanup items that I don't use anymore.

At the moment I have something like this:
[scene 1] -> many resources -> player walks to [scene 2] -> release scene 1 resources -> load scene2 resources

Its fast at the moment, but I need to learn to set to nil after a object:release()