leafo/moonscript

In-place appending an item to an array

bpj opened this issue · 3 comments

bpj commented

I miss an operator for in-place appending an element to an array, e.g.

array #= item

as syntactic sugar for the common idioms

array[#array+1] = item


table.insert array, item

I guess you could overload ..= but then you would have to always check if LHS is a table. While #= may not be immediately obvious it seems reasonable to me. I guess &= using an as yet unused character might work, although then people might expect & to concatenate/merge arrays/tables, which would be nice to have, but probably considerably harder to implement.

(Apologies if this is a duplicate. I did search the existing issues for relevant keywords but there seemed not to be anything similar.)

& is a valid operator in Lua, so &= probably shouldn't be used. I'd be more fine with #= given no one should be assigning an int to what was previously a length-able object.

Found myself needing this operator while writing a module that makes use of many of these. I agree it could be really nice to have these. I'd be fine with #=.

[ ] is comprehensive and clean. imho

array []= item