lua-users home
lua-l archive

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


On Mon, Nov 2, 2015 at 12:32 AM, Niccolo Medici <niccolomedici@gmail.com> wrote:
> Officially, it's not correct to do "table.unpack{nil, 'something',
> 'another'}" because the nil makes it legitimate for table.unpack() to
> regard the length of the table as 0.
>
> However, all Lua implementations I've checked (Lua 5.1, 5.2, 5.3, JIT)
> do calculate #{nil,a,b} to be 2, not 0. Let's assuming a and b are
> never nil.
>
> So I was wondering if this is a special case we can trust to always work.
>
> <comment>
>
> Why do I ask this?
>
> Because sometimes I need to wrap one of the system functions. Such
> functions return (nil, errmsg, errcode) on error. So I have the
> following pattern in my code:
>
>     local ret = { file:close() }
>     -- do something
>     return table.unpack(ret)
>
> I know I can rewrite is as:
>
>     local ret = table.pack( file:close() )
>     -- do something
>     return table.unpack(ret, 1, ret.n)
>
> But sometimes I do "ret = { nil, a, b }" explicitly and it'd be
> cumbersome to set the "n" field myself in all places.
>
> </comment>
>

I had the same issue and I did something similar. For me, this helped:

```
local _unpack = table.unpack or unpack
table.unpack = function(list, i, j)
  return _unpack(list,i or 1, j or list.n or nil)
end
```

I understand that this does not *solve* your problem, 100%. For me,
this works, because it pushes the blame to the part of your code that
*makes* the potentially hole-y list, which is easier than guessing
about when you might get one or not.

-Andrew