I have some code that wants to do grab some extra return values from a function and pass them forward latter on:
local ok, ... = coroutine.resume(co)
do_stuff(ok)
return ...
However, this won't run since the ...
on the variable assignment is a syntax error.
I could work around this limitation by using the old "functions arguments and variables are equivalent" trick and an immediately-invoked function
return (function(ok, ...)
do_stuff(ok)
return ...
)(coroutine.resume(co))
but I imagine doing so wouldn't be very idiomatic or efficient. Are there more reasonable ways to solve this problem of handling the remaining values returned from the resume
call?
EDIT: By the way, this needs to work with nil
values in the extra arguments
EDIT2: Looks like using the immediately invoked function was the best way all along.
IMHO, the best way is passing vararg as parameter to helper function as you have done in your question.
The alternative way is "pack-unpack":
-- Lua 5.2 only
local t = table.pack(coroutine.resume(co))
do_stuff(t[1])
return table.unpack(t, 2, t.n)
The idiomatic way to do this with an unknown number of return values is to wrap the function call in a table constructor:
local t = { coroutine.resume(co) }
do_stuff(table.remove(t, 1))
return unpack(t) -- table.unpack(t) in lua 5.2
While this also involves creating a temporary object, it should be a lot quicker than using a closure, and it's certainly a lot neater.
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