Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way to handle variadic values in a variable assignment?

Tags:

lua

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.

like image 207
hugomg Avatar asked Jan 29 '13 08:01

hugomg


2 Answers

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)
like image 144
Egor Skriptunoff Avatar answered Nov 03 '22 10:11

Egor Skriptunoff


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.

like image 44
furq Avatar answered Nov 03 '22 11:11

furq