lua-users home
lua-l archive

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

On 2015-Sep-27 (Sun) at 10:25 (-0300), Soni L. wrote:

>> Would this work?
>> list=table.pack(1,2,3,nil,4,5,nil,nil,6,7)
>> local n=0
>> for i=1,list.n do
>>         if list[i]~=nil then
>>                 n=n+1
>>                 list[n]=list[i]
>>                 list[i]=nil
>>         end
>> end
>> list.n=n
>> for k,v in ipairs(list) do print(k,v) end


   No, it would not work.

   If 'list' has some non-nil elements at its start, they will get
   set to nil by the statement 'list[i]=nil'.

   You could fix it by instead writing

      if i > n then list[ i ] = nil end

   but at this stage, the logic may be getting slightly clumsy.
   Dirk's solution, although it involves an additional for-loop,
   seems a little clearer.


Joseph Manning / Computer Science / UCC Cork Ireland /