Search code examples
luacalllua-tablelove2d

Can I call a table inside itself in Lua?


So I'm trying this:

buttons = {

{imageNothing = love.graphics.newImage("buildingButtonNotSelected.png"), imageHovering = love.graphics.newImage("buildingButtonHovering.png"), imageSelected = love.graphics.newImage("buildingButton.png"),imgW = buttons[1].imageNothing:getWidth(), imgH = buttons[1].imageNothing:getHeight(), imgX = windowWidth - buttons[1].imgW, imgY = windowHeight - buttons[1].imgH, selected = false, hovering = false}

}

I am currently getting this error: Attempt to index global 'buttons' (a nil value)

Any idea?


Solution

  • You can't.

    The table isn't created until the table constructor is evaluated. So buttons isn't defined inside the table constructor.

    You can initliaze buttons without using `buttons inside the table constructor, then add those fields later.

    buttons = {
      {
        imageNothing = love.graphics.newImage("buildingButtonNotSelected.png"), 
        imageHovering = love.graphics.newImage("buildingButtonHovering.png"), 
        imageSelected = love.graphics.newImage("buildingButton.png"),
        selected = false, 
        hovering = false
      }
    }
    
    buttons.imgW = buttons[1].imageNothing:getWidth()
    buttons.imgH = buttons[1].imageNothing:getHeight()
    buttons.imgX = windowWidth - buttons[1].imgW
    buttons.imgY = windowHeight - buttons[1].imgH