Search code examples
lualua-table

How to 'unpack' table into function arguments


I'm trying to call a function in Lua that accepts multiple 'number' arguments

function addShape(x1, y1, x2, y2 ... xn, yn)

and I have a table of values which I'd like to pass as arguments

values = {1, 1, 2, 2, 3, 3}

Is it possible to dynamically 'unpack' (I'm not sure if this is the right term) these values in the function call? Something like..

object:addShape(table.unpack(values))

Equivalent to calling:

object:addShape(1, 1, 2, 2, 3, 3)

Apologies if this is a totally obvious Lua question, but I can't for the life of me find anything on the topic.


UPDATE

unpack(values) doesn't work either (delving into the method addShape(...) and checking the type of the value passed reveals that unpackis resulting in a single string.


Solution

  • You want this:

    object:addShape(unpack(values))
    

    See also: http://www.lua.org/pil/5.1.html

    Here's a complete example:

    shape = {
      addShape = function(self, a, b, c)
        print(a)
        print(b)
        print(c)
      end
    }
    
    values = {1, 2, 3}
    shape:addShape(unpack(values))