Codea crash because of this code

There is something wrong with this code. Codea constantly crashes after this method is called for some 500 times from the draw().

function Screen:scroll(pos, dim, lines)
    pushStyle()
    spriteMode(CORNER)
    rectMode(CORNER)
    fill(0, 0, 0, 255)
    noStroke()
    noSmooth()
    
    local topLeft = self:calculateActualLoc(pos)
    local bottomRight = vec2(topLeft.x+dim.x*8, topLeft.y-dim.y*8)
    if lines < 0 then
        local movedArea = self.buffer:copy(topLeft.x-1, bottomRight.y, dim.x*8, (dim.y+lines)*8+1)
        setContext(self.buffer)
        sprite(movedArea, topLeft.x-1, topLeft.y-movedArea.height)
        rect(topLeft.x-1, bottomRight.y, dim.x*8, -lines*8)
    elseif lines > 0 then
        local movedArea = self.buffer:copy(topLeft.x-1, bottomRight.y+lines*8, dim.x*8, (dim.y-lines)*8+1)
        setContext(self.buffer)
        sprite(movedArea, topLeft.x-1, bottomRight.y-1)
        rect(topLeft.x-1, topLeft.y-lines*8, dim.x*8, lines*8)
    end
    
    setContext()
    popStyle()
end

I narrowed it further to the call to image:copy() but I can’t reproduce it in a separate plain simple program. If the copy line is commented out, no crash but of course it doesn’t do what it’s supposed to.

self.buffer is just image(pixelDim.x, pixelDim.y) whose contents are drawn via both image:set and graphic operations via setContext(self.buffer) just like what this method does, all that before it’s sprited onto screen.

The symptoms look to me that there’s some critical resource leak here when image:copy is called, causing Codea to crash. But I’m not sure why same problem doesn’t show up when I simplified it into a plain separate program. I need help to get around this problem.

Try putting collectgarbage() at the start of Screen:scroll. There’s probably a problem with memory not being cleared fast enough by itself.

@dave1707 THANK YOU! It works beautifully. Do you know under what conditions that memory doesn’t get cleared fast enough? When does it get cleared anyway?

@tsukit I think your code exposes a bug with how Lua interacts with C here. Lua doesn’t think it’s using a lot of memory since it’s just holding onto light weight pointers to the image data, in C the memory keeps being allocated by the image library, but Lua doesn’t know that it should probably collect garbage because those light pointers refer to large amounts of memory

We need to somehow track the memory usage outside of Lua and trigger a Lua GC if it starts getting out of hand

@Simeon that makes sense. Thanks for further info.