Page 1 of 1

Why can't I store this value in variable, yet I can use it normally?

Posted: Wed Nov 24, 2021 7:31 am
by tommcjeff
So I'm trying to make a simple scrolling platformer, but when I'm making it scroll, I came across this line:

Code: Select all

love.graphics.polygon("fill", objects.ground.body:getWorldPoints(objects.ground.shape:getPoints()))
I tried to replace it with this:

Code: Select all

local allpoints = objects.ground.body:getWorldPoints(objects.ground.shape:getPoints())
love.graphics.polygon("fill", allpoints)
and it errored with:
Error

main.lua:46: Number of vertex components must be a multiple of two

Would anyone know why this happens? I'm new to love2d so I'm not sure why this is happening.

Re: Why can't I store this value in variable, yet I can use it normally?

Posted: Wed Nov 24, 2021 1:20 pm
by BrotSagtMist
This function returns multiple number values, Assignment with = only work for one single value.
You save the x value of the first point and discard the rest, obviously this cannot get drawn.
The workaround is to turn all returns into a table:
local allpoints = {objects.ground.body:getWorldPoints(objects.ground.shape:getPoints())}

Re: Why can't I store this value in variable, yet I can use it normally?

Posted: Wed Nov 24, 2021 1:51 pm
by MrFariator
You can assign multiple return values from a function with the assignment operator, you just need to introduce additional variables.

Code: Select all

local p1x, p1y, p2x, p2y, p3x, p3y = objects.ground.body:getWorldPoints(objects.ground.shape:getPoints())
love.graphics.polygon("fill", p1x, p1y, p2x, p2y, p3x, p3y)
Of course, this works mostly if you already know ahead of time how many points your polygon will have, because as far as I know, love.graphics.polygon will fail if any of the passed variables is nil.

Wrapping the points into a table like BrotSagtMist pointed out works, too. However, this is not advisable because you'll be creating a new table every time such code is run (every frame when drawing), which is rather needlessly costly. As such, for any arbitrarily sized polygons, you're better off using the first line of code in your opening post.

Re: Why can't I store this value in variable, yet I can use it normally?

Posted: Thu Nov 25, 2021 7:51 am
by zorg
also, love.graphics.polygon can accept variadic number of arguments (i think, look at the wiki to make sure) after the first one, so that's also the reason why the first code block works, since all passed arguments will be used.