lua-users home
lua-l archive

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




On Sunday, August 3, 2014, Dirk Laurie <dirk.laurie@gmail.com> wrote:
2014-08-03 7:44 GMT+02:00 Andrew Starks <andrew.starks@trms.com>:

> Return the keys in a table (any order):
>
> ```
> local function list_keys(t, ...)
>     if next(t, (...)) then
>         return list_keys(t, next(t, (...)), ...)
>     else
>         return ...
>     end
> end

I know, the point is to illustrate that one can do the unexpected
with vararg, but if I just wanted to return the keys, I would do it
thus:

function return_keys(tbl)
   local t={}
   for k in next,tbl do t[#t+1]=k end
   return table.unpack(t)
end

Of course, as your test

> print("-->",table.concat({list_keys(test)}, "\n-->\t"))

demonstrates, it's more useful to return a table of keys
and if necessary do the unpacking after the call.


I really wanted the values without the table. The unpack was for pretty printing. 

Your premise was correct. I just thought it was cool. No need to bring pragmatism into this, Dirk. :)

-Andrew