Reputation: 1801
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
.
Upvotes: 37
Views: 63743
Reputation: 2012
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
Upvotes: 17
Reputation: 29493
This is not an answer about unpack, but a suggestion to use a different technique. Instead, do
function object:addShape(values)
for i,v in ipairs(values) do
x,y = v.x, v.y
...
end
end
function getPairs(values)
xyPairs = {}
for i=1,#values,2 do
v = {x=values[i], y=values[i+i] }
table.insert(xyPair, v)
end
return xyPairs
end
values = {1, 1, 2, 2, 3, 3}
object:addShape(getPairs(values))
The amount of work to be done should be similar as unpacking and the additional processing you will have to do in addShape() to support variable number of named arguments.
Upvotes: -7
Reputation: 249153
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))
Upvotes: 45