lua-users home
lua-l archive

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



hello Luiz,

               local t=table.pack(...)
               local n=t.n
               t.n=nil 

I was thinking of #t, but I saw t.n. Looks a bit strange to me. Please help me out

Regards, \Emeka
On Wed, May 9, 2012 at 1:52 PM, Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br> wrote:
> Given a function that returns multiple values, is there a way to construct a table, but where each value is assigned a name rather than an index

You'll need a helper function:

       function namedtable(name,...)
               local t=table.pack(...)
               local n=t.n
               t.n=nil
               for i=1,n do
                       local v=t[i]
                       t[i]=nil
                       t[name[i] or 0]=v
               end
               return t
       end

       function f()
               return 100,200,400
       end

       local t=namedtable({"day", "month", "year"},f())
       for k,v in pairs(t) do print(k,v) end




--
Satajanus  Nig. Ltd