lua-users home
lua-l archive

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


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 a()
  -- could cause an error, could return different numbers of values
  return 1, nil, 2

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

print(a())   --> 1 nil 2
print(b())   --> 1 nil 2

But, with the new LuaJIT 2 beta:

print(a())   --> 1 nil 2
print(b())   --> 1

That's not a bug, it's just different undefined behavior. Anyone know how to do this in a defined manner? (unpack(r, 1, <maximum possible number of return values of a>) would work, but I'd like to do better).