lua-users home
lua-l archive

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


On Wed, Nov 4, 2009 at 3:24 PM, Geoff Leyland <geoff_leyland@fastmail.fm> wrote:
> 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!

Use:

function b()
  local t = pack(pcall(a));
  if not r[1] then error("something") end
  return unpack(r, 2, r.n)
end

(this is what Roberto's code meant to be I think)

Note there is no closure cost here.


-- 
-Patrick Donnelly

"Let all men know thee, but no man know thee thoroughly: Men freely
ford that see the shallows."

- Benjamin Franklin