Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'unpack' table into function arguments

Tags:

lua

lua-table

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.

like image 674
codinghands Avatar asked Mar 16 '14 06:03

codinghands


People also ask

How do I unpack a table in Lua?

unpack() function in Lua programming. When we want to return multiple values from a table, we make use of the table. unpack() function. It takes a list and returns multiple values.

What is argument unpacking in Python?

Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .

What do you understand by the terms packing and unpacking?

Tuple packing refers to assigning multiple values into a tuple. Tuple unpacking refers to assigning a tuple into multiple variables.

What are the parameters and arguments?

The values that are declared within a function when the function is called are known as an argument. The variables that are defined when the function is declared are known as parameters. These are used in function call statements to send value from the calling function to the receiving function.


2 Answers

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))
like image 140
John Zwinck Avatar answered Oct 17 '22 15:10

John Zwinck


Whoever comes here and has Lua version > 5.1 unpack is moved into the table library so you can use: table.unpack

For more info: https://www.lua.org/manual/5.2/manual.html

like image 6
HSLM Avatar answered Oct 17 '22 17:10

HSLM