Page 1 of 1
Any way to extend love objects? [Solved]
Posted: Sat Jun 15, 2013 2:32 am
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
Re: Any way to extend love objects?
Posted: Sat Jun 15, 2013 2:54 am
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.
Re: Any way to extend love objects?
Posted: Sat Jun 15, 2013 4:01 am
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!
Re: Any way to extend love objects? [Solved]
Posted: Sun Jun 16, 2013 3:30 pm
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)