lua-users home
lua-l archive

Re: [PUZZLE] Appending to a list

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


On Fri, Sep 8, 2017 at 12:31 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
> I used to have the following statement in nearly all of my programs.
>
> local append = tinsert
>
> where tinsert is a local variable with value table.insert. The idea is
> that when the `pos` parameter is omitted, I prefer for the sake of
> easy reading to use a different name.
>
> Today, I needed to do this instead:
>
> local append = function(tbl,x) tinsert(tbl,x) end
>
> Why would that be?
It's as Daurnimator said.
While it does nothing toHowever, I like:
local function append(tbl, x, ...)
 if x == nil then
 return tbl
 else
 tinsert(tbl, x)
 return append(tbl, ...)
 end
end
or the golf version...
local function append(tbl, x, ...)
 return x == nil and tbl or append(tinsert(tbl, x) or tbl, ...)
end
Sorry. I saw puzzle and felt like participating. :)
>
> Once you have figured it out, the next question is: should I have
> expected table.insert to behave that way or is it a deviation from
> what the manual says?
>
I agree that optional middle parameters are extremely clever and
tricky and sometimes convenient.
- Andrew Starks

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