lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Thanks Roberto,

On 5/11/2009, at 9:09 AM, Roberto Ierusalimschy wrote:

How do you return multiple values from a function that pcalls a function
that returns an unknown number of values possibly including nil in a
manner that doesn't involve undefined behaviour?

[...]

function b()
 local status, r = pcall(function() return { a() } end)
 if not r then error("nicely handled error!") end
 return unpack(r)
end

[...]


function pack (...)
 return { n = select("#", ...); ... }
end

function b()
 local r = pack(pcall(function() return { a() } end))
 if not r[1] then error("nicely handled error!") end
 return unpack(r, 2, r.n)
end

?


Excuse me for causing confusion by writing "if not r" where I meant "if not status", and for the case of what I *meant*, it'd be

local status, r = pcall(function() return pack(a()) end)
if not status [...]

It has the advantage over Florian's that you only write pack once and you handle the error in b(), not in the helper function, whereas Florian's avoids the packing and unpacking. I think they have the same number of closures?

Anyway, thanks to you both!

Cheers,
Geoff