lua-users home
lua-l archive

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


Am 24.11.2013 10:17 schröbte steve donovan:
On Sun, Nov 24, 2013 at 2:38 AM, Tom N Harris <telliamed@whoopdedo.org> wrote:
     table.insert(list, pos, value, ...)

I'd support this if it could be done significantly faster than than a
chain of inserts. Time for us to start playing with C, perhaps?

I'm unhappy with `table.insert` as a standard function anyway:
* There are more general/useful functions (e.g. the one below which can replace `table.insert` and `table.remove`, and can deal with multiple elements in one go). * It can be implemented in 20 lines of Lua (half of which is argument checking). * The most common use-case (appending) is already almost twice as fast when written in Lua as `t[ #t+1] = v` (`t[ n ], n = v, n+1` is even faster) and doesn't need an extra library function. (Inserting 100 elements at the front in pure Lua is 3 times slower using normal array operations, and 8 times slower for raw accesses). * `table.insert` does not handle proxy-tables or userdata-containers (it will respect `__len` metamethods for tables though, not sure if this is intentional).


But ...  an existing function that acquires extra arguments leads to
surprising new behaviour, e.g. table.insert(t,1,str:gsub('%W','_'))
will insert _two_ values in the table.

It will throw an error now, so no problems with existing code ...


So I'd vote for table.insertvalues....


I'm not sure varargs are appropriate here anyway. Maybe
    table.insertvalues( list, [pos,] list2 )
or (my favorite):
table.swissarmyknife( list, [lstart=#list+1, [lend=lstart,]] list2 [,l2start=1 [,l2end=#list2]] )


steve d.


Philipp