[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Is it safe to unpack { nil, a, b } ?
- From: Niccolo Medici <niccolomedici@...>
- Date: Mon, 2 Nov 2015 08:32:54 +0200
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>
- Follow-Ups:
- Re: Is it safe to unpack { nil, a, b } ?, Pierre Chapuis
- Re: Is it safe to unpack { nil, a, b } ?, Dirk Laurie
- Re: Is it safe to unpack { nil, a, b } ?, Soni L.
- Re: Is it safe to unpack { nil, a, b } ?, Andrew Starks