Help with constructor
Posted: Fri May 05, 2017 7:53 pm
Fairly new to lua & love2d.
Here's a simplified example of what i'm trying to do...
this should draw five 100x25 cubes 5 pixels apart from each other across the top of the screen (unless i'm screwing something else up as well)
this fills my objectlist with 5 values, but they all have the same attributes; they are all drawn at the same (last) location. I suppose i'm missing some sort of actual constructor in the myCube:create() function. But I cannot find a simple solution to this, and i'm a bit confused when I start looking up constructors. Examples are showing rather lengthy constructors with _init and metatables. I don't really understand it at a glance.
I would really think love2d, as a library, would have some sort of simple solution to instancing objects. perhaps i'm wrong.
any help/advice would be appreciated.
Here's a simplified example of what i'm trying to do...
this should draw five 100x25 cubes 5 pixels apart from each other across the top of the screen (unless i'm screwing something else up as well)
Code: Select all
objectlist = {}
myCube = {
x = nil,
y = nil,
width = nil,
height = nil
}
function myCube:create(x,y,width,height)
self.x = x
self.y = y
self.width = width
self.height = height
return self
end
function myCube:draw()
love.graphics.rectangle("fill",self.x,self.y,self.width,self.height)
end
function love.load()
width = 100
height = 25
spacing = 5
for i = 1,5 do
cube = myCube:create(i*spacing + i*width,5,width,height)
table.insert(objectlist,i,cube)
end
end
function love.draw()
for k,v in ipairs(objectlist) do
v:draw()
end
end
I would really think love2d, as a library, would have some sort of simple solution to instancing objects. perhaps i'm wrong.
any help/advice would be appreciated.