lua-users home
lua-l archive

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


> On Jan 4, 2017, at 4:32 AM, Soni L. <fakedme@gmail.com> wrote:
> 
>> On 04/01/17 02:24 AM, 聂威 wrote:
>> dear list,
>> 
>> I have noticed that `table.unpack(list [,i [, j]])` will NOT regards the `n` field in the `list` table,
>> 
>> I know I can write it like this:
>> 
>> ```
>> table.unpack(list, 1, list.n)
>> ```
>> 
>> but will it be a good idea to make it read `n` field in table.unpack?
>> 
>> thanks and happy new year!
>> 
>> ps:
>> 
>> table.pack in Lua 5.3 manual:
>> 
>> ```
>> 
>> 
>>      |table.pack (···)|
>> 
>> Returns a new table with all parameters stored into keys 1, 2, etc. and with a field "|n|" with the total number of parameters. Note that the resulting table may not be a sequence.
>> 
>> ```
> 
> Here's a better idea:
> 
> Why not make table.pack return a table, the value 1, and the total number of parameters?
> 
> That way, table.unpack(table.pack(f())) is equivalent to f().

But why? There is no practical reason to immediately unpack what was just packed. At some point you need to access the packed values.

Consider:

   local args, from, to = table.pack(...)
   -- or argsvalues = table.pack(table.pack(...))?
   -- or argstable = {table.pack(...)}?
   local r = {n=from}
   for i = from, to do
     r[i] = process(args[i])
   end

versus, IMHO clearer:

   local args = table.pack(...)
   local r = {n=args.n}
   for i = 1, args.n do
      r[i] = args[i]
   end

Cheers,
Gary