Search code examples
lualove2d

Am I able to use table.concat as a set of arguments?


I'm using LOVE2D to get used to lua a bit more, and I am trying to call a function to make a circle appear on screen, there's 5 arguments, and I have a table known as 'button' with the required arguments in it. I want to use table.concat to to fill in all the blank arguments but it won't let me. Is there anyway to do this?

function toRGB(r,g,b)
    return r/255,g/255,b/255
end

function love.load()
    button = {}
    button.mode = "fill"
    button.x = 0
    button.y = 0
    button.size = 30
end

function love.draw()
    love.graphics.setColor(toRGB(60,60,60))
    love.graphics.circle(table.concat(button))
end

Solution

  • table.concat returns a string. That's not what you want.

    To get a list of table elements use table.unpack. But this function does only work with tables that have consecutive numeric indices starting from 1.

    Also love.graphics.circle accesses its parameters by position, not by name. Hence you have to ensure that the expression list you put into that function has the right order.

    So something like:

    button = {"fill", 0, 0, 30}
    love.graphics.circle(table.unpack(button))
    

    would work.

    If you're using other table keys as in your example you'll have to write a function that returns the values in the right order.

    In the simplest case

    button = {}
    button.mode = "fill"
    button.x = 0
    button.y = 0
    button.size = 30
    button.unpack = function() return button.mode, button.x, button.y, button.size end
    love.graphics.circle(button.unpack())
    

    Or you can do something like this:

    function drawCircle(params)
      love.graphics.circle(params.mode, params.x, params.y, params.size)
    end
    drawCircle(button)
    

    There are many other ways to achieve this.