Page 1 of 1

OOP Map Question

Posted: Sun Mar 13, 2022 11:58 am
by NoreoAlles
I have a project in wich i have a Block class

Code: Select all

Block = {}
Block.__index = Block

function Block.new(x, y, r, g, b )
    local instance = setmetatable({}, Block)
    instance.x = x 
    instance.y = y 
    instance.width = 50
    instance.height = 50
    instance.r = r 
    instance.g = g 
    instance.b = b
    instance.body = love.physics.newBody(world, instance.x, instance.y, "static")
    instance.shape = love.physics.newRectangleShape(instance.width, instance.height)
    instance.fixture =love.physics.newFixture(instance.body, instance.shape)
    return instance
end

function Block:draw()
    love.graphics.rectangle("fill", self.x - self.width / 2, self.y - self.height / 2, self.width, self.height)
end
    
and i have a problem with drawing these Blocks, when theyre created in a for loop.

Code: Select all

Blocks = {0, 0, 1, 1, 1, 0}
for i, block in ipairs(Blocks) do
	Block.new(--some magic involving i)
end
 
I can imagine you somehow have to put the blocks created in the loop into a table, wich you then draw using my Block:draw() function, but i cant grasp this.

Re: OOP Map Question

Posted: Sun Mar 13, 2022 2:44 pm
by darkfrei

Code: Select all

Blocks = {0, 0, 1, 1, 1, 0}
for index, value in ipairs(Blocks) do
	local newBlock = Blocks.new(--some magic involving index and value)
end

Re: OOP Map Question

Posted: Sun Mar 13, 2022 3:28 pm
by nehu
from what i understand, you want to call the :draw function on all of blocks created in a loop. :huh:
First you store the new blocks in a table

Code: Select all

blocks = {} --we define the table where we will store the blocks
for i = 1, 10 do --example 'for' loop, this one iterates from 1 to 10 and stores the progress in the variable i

	blocks[#blocks + 1] = Block.new(i*50,i*50,1,0,0) --creates a blocks and stores it in a new index of 'blocks'.
	--the # returns the quantity of elements in a table, only works with elements ordered from 1 to inf

end
and for drawing then

Code: Select all

for i, block in ipairs(blocks) do --iterates over all the elements of blocks, the list where we stored the blocks

	--i is the index where the function is at. block is the equivalent of blocks[i], it's the value of the index that the loop is at

	block:draw() --calls the draw function for drawing the block

end
the loop can also work using

Code: Select all

blocks[i]
, but that will overwrite any existing elements, so if there are blocks in the list already, it could make unwanted things :o:
anyways, this could work for any loop, you just need to store the new blocks in the 'blocks' table :awesome:

hope it helped ! :crazy:

Re: OOP Map Question

Posted: Sun Mar 13, 2022 4:54 pm
by NoreoAlles
nehu wrote: Sun Mar 13, 2022 3:28 pm ...
hope it helped ! :crazy:
Yes it did, thanks you so much. :P