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 unpack
is resulting in a single string
.
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.
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, * .
Tuple packing refers to assigning multiple values into a tuple. Tuple unpacking refers to assigning a tuple into multiple variables.
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.
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))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With