lua-users home
lua-l archive

Re: Little fun with vararg

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


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.

AltStyle によって変換されたページ (->オリジナル) /