I have a function in Lua that gives a variable number of outputs. How can I get all its outputs, regardless of how many outputs it has?
function my_function()
-- whatever
end
outputs_list = my_function()
The above example doesn't work because outputs_list gets only the first output of the function, and all the others are discarded.
I want outputs_list to contain all the outputs of the function so I can retrieve them later.
I think this is equivalent in python to doing *outputs_list = my_function()
In general, you can capture the values into a table
but it may not be a sequence if the function returns nil values that create holes in the list.
selectmay be used to choose where to begin capturing return values.In Lua 5.2+, you also have access to
table.pack(...), whichThe caveat about the resulting table not being a sequence means that looping over all the returned values may require a numeric
for, instead of a generic one usingipairs.The opposite function is
table.unpack.In Lua 5.1, you can polyfill
table.packas