How to call upon a table?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
JellyBones
Prole
Posts: 2
Joined: Tue Sep 04, 2018 1:28 am

How to call upon a table?

Post 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!
JellyBones
Prole
Posts: 2
Joined: Tue Sep 04, 2018 1:28 am

Re: How to call upon a table?

Post 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
MrFariator
Party member
Posts: 543
Joined: Wed Oct 05, 2016 11:53 am

Re: How to call upon a table?

Post 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.
User avatar
pgimeno
Party member
Posts: 3635
Joined: Sun Oct 18, 2015 2:58 pm

Re: How to call upon a table?

Post 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.
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot] and 6 guests