Patching new methods on resources

I found that I was often writing code like the following to draw images based on x, y, width and height information (since that’s what Inkscape shows when you click an element):

ticker_bg:draw(100, 964, 100 + 1820, 116)

The “100 +” was the reminder to me that I’ve slid this image over by 100 px and let the width be visible as 1820 px.

To avoid that, I wrote a helper:

draw_image_xywh(ticker_bg, 100, 964, 1820, 116)

However, that stuck out as looking different than the other draw method calls. So, my idea was to patch the draw_xywh method onto the regular image resource.

local original_load_image = resource.load_image

resource.load_image = function(opt)
    local image = original_load_image(opt)

    return {
        draw = function(self, x1, y1, x2, y2, alpha)
            image:draw(x1, y1, x2, y2, alpha)
        end,

        draw_xywh = function(self, x, y, w, h, alpha)
            image:draw(x, y, x + w, y + h, alpha)
        end
    }
end

That lets me write ticker_bg:draw_xywh(100, 964, 1820, 116).

However, my concern is that this shenanigans might be adding a significantly slower wrapper, since it feels like load_image and drawing would be highly optimized to avoid the Lua interpreter. So, is this a really bad idea? Something silly but harmless? Thanks!

Totally fine. I doubt you can notice any difference at all. The load_image and draw is still identical after all and the interpreter doesn’t really care what that are named.

1 Like