Page 1 of 1

How to call upon a table?

Posted: Tue Sep 04, 2018 1:53 am
by JellyBones
Hi, I'm new both to Love2D and the forums!

I'm trying to create an outline around each box listed in an array for a WIP inventory system, with:

Code: Select all

        local slots = {
            {x=770,y=446,w=30,h=30}, --1
            {x=806,y=446,w=30,h=30}, --2
            {x=842,y=446,w=30,h=30}, --3
            {x=878,y=446,w=30,h=30}, --4
            {x=808,y=482,w=30,h=30}, --5
            {x=806,y=482,w=30,h=30}, --6
            {x=842,y=482,w=30,h=30}, --7
            {x=878,y=482,w=30,h=30}  --8
        }

        for i = #slots[1], do
             ( love.graphics.setColor( 1, 0, 0 )
             love.graphics.rectangle( line, x, y, w, h ) )    
Although this gives me

Syntax error: main.lua:34: unexpected symbol near 'do'


What would be the proper/best way to draw an outline for each element? Thanks!

Re: How to call upon a table?

Posted: Tue Sep 04, 2018 3:25 am
by JellyBones
Figured out the issue in my syntax from https://www.lua.org/pil/4.3.5.html

This works perfectly:

Code: Select all

        for _, v in pairs(slots) do
            love.graphics.rectangle('line', v.x, v.y, 30, 30)
        end

Re: How to call upon a table?

Posted: Tue Sep 04, 2018 8:31 am
by MrFariator
While using a 'pairs' for loop also works, do keep in mind that the syntax issue with your original code was that you didn't define the first two expressions of your for loop properly. The following would be the correct way to write what you tried to do.

Code: Select all

love.graphics.setColor( 1, 0, 0 ) -- we don't need to change the draw color constantly if it's static
for i = 1, #slots do
  love.graphics.rectangle( line, slots[i].x, slots[i].y, slots[i].w, slots[i].h ) 
end
Additionally, for future reference the order in which 'pairs' iterates through a table isn't specified, so things could get hairy if the draw order mattered.

Re: How to call upon a table?

Posted: Tue Sep 04, 2018 3:37 pm
by pgimeno
Performance wise, ipairs() is also faster than pairs(). And a numeric loop like the one MrFariator posted is faster than ipairs. I haven't tested whether LuaJIT automatically caches common subexpressions like slots[i], but the performance guide says it does, therefore that loop should give maximum performance as written.