Any way to extend love objects? [Solved]

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
mcjohnalds45
Prole
Posts: 18
Joined: Sat Jun 02, 2012 12:08 pm

Any way to extend love objects? [Solved]

Post by mcjohnalds45 »

Is there any way to add functions to love objects from within love2d without having to compile your own love2d?

E.g

Code: Select all

function love.Image:getSize()
	return self:getWidth(), self:getHeight()
end

hamster = love.graphics.newImage('hamster.png')

print(hamster:getSize()) -- Prints 128, 128
Last edited by mcjohnalds45 on Sat Jun 15, 2013 4:02 am, edited 2 times in total.
User avatar
slime
Solid Snayke
Posts: 3161
Joined: Mon Aug 23, 2010 6:45 am
Location: Nova Scotia, Canada
Contact:

Re: Any way to extend love objects?

Post by slime »

Here is one way, but it's not particularly elegant:

Code: Select all

do
    local function getImageSize(image)
        return image:getWidth(), image:getHeight()
    end

    local _newImage = love.graphics.newImage
    function love.graphics.newImage(...)
        local img = _newImage(...)
        getmetatable(img).getSize = getImageSize

        love.graphics.newImage = _newImage
        return img
    end
end

myimage = love.graphics.newImage("hamster.png")
print(myimage:getSize())
Personally I'd recommend against messing with LÖVE's objects like that though. You can just use a getImageSize function to accomplish the same thing without modifying anything else.
User avatar
mcjohnalds45
Prole
Posts: 18
Joined: Sat Jun 02, 2012 12:08 pm

Re: Any way to extend love objects?

Post by mcjohnalds45 »

I just felt it made more sense to put functions like that into the only object it's going to be used on anyway. Thanks for that code though, I never think of doing that!
User avatar
kikito
Inner party member
Posts: 3153
Joined: Sat Oct 03, 2009 5:22 pm
Location: Madrid, Spain
Contact:

Re: Any way to extend love objects? [Solved]

Post by kikito »

I have used metatables to do it in the past, but it was very implementation-dependent (could work on 0.8.x and fail in 0.9.x)
When I write def I mean function.
Post Reply

Who is online

Users browsing this forum: Semrush [Bot] and 3 guests