Page 1 of 1

Drawing lines using a table (why doesn't it work?)

Posted: Sun Feb 19, 2017 6:00 pm
by sdeban
Hi, I'd like to draw some lines using a table of coordinates. Oddly, when I create a table manually ('trapezoid' below), the lines draw fine. When I create the table in a loop from random numbers, it does not draw as lines, but will draw as points. In the code below, 'trapezoid' works fine for both, but 'coords' only works for points. Puzzling...

Code: Select all

        trapezoid = {200,50, 400,50, 500,300, 100,300, 200,50}
	coords = {}   
	for i = 1, 10 do  
		x = math.random(5, 500)   
		y = math.random(5, 500)
		coords[i] = {x, y}   
	end
	
	function love.draw(dt)
		love.graphics.line(coords)
		love.graphics.points(coords)
		love.graphics.line(trapezoid)
		love.graphics.points(trapezoid)
        end

	

Re: Drawing lines using a table (why doesn't it work?)

Posted: Sun Feb 19, 2017 6:21 pm
by Santos
Hi sdeban,

love.graphics.line and love.graphics.points are inconsistent in the table structure they accept.

A table with alternating x/y positions will work for both, like your manually created table and this random table:

Code: Select all

for i = 1, 10, 2 do  
	x = math.random(5, 500)   
	y = math.random(5, 500)
	coords[i] = x
	coords[i + 1] = y  
end
However when the x/y pairs are in tables, like your randomly created table or this table, it only works with points.

Code: Select all

trapezoid = {{200,50}, {400,50}, {500,300}, {100,300}}
	
function love.draw(dt)
	love.graphics.line(trapezoid)
	love.graphics.points(trapezoid)
end
I believe the reason for the inconsistency is that points can have optional colors for each point. For example...

Code: Select all

trapezoid = {{200,50, 255,255,0}, {400,50, 255,0,255}, {500,300, 0,255,255}, {100,300, 0,255,0}}
	
function love.draw(dt)
	love.graphics.points(trapezoid)
end

Re: Drawing lines using a table (why doesn't it work?)

Posted: Sun Feb 19, 2017 7:59 pm
by sdeban
Thank you Santos. That works great. I would never have figured that out.