lua-users home
lua-l archive

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

Here is a suggestion I've formulated in the "Definition of table.insert" thread. Now I've added some more details.

table.insert(table, pos, ...)
Inserts values '...' at position 'pos' in 'table', shifting up other elements to open space, if necessary. Returns number of elements inserted (i.e. the number of parameters passed as '...'). Alternatively, it could be made to return index of the last inserted element. Negative or zero 'pos' meant counting from the end of table. E.g. if 'pos' is 0, #t+1 is used and arguments are appended to the table.

So, this is backwards incompatible with 2-arguments 'table.insert(t,x)'. There'sno special case for 'nil'. 1) The natural use case is when many elements must be inserted. Currently this can be done with a custom implementation or by slowly inserting elements 1 by 1.
2) Here's another use case I really like:
local t = {}
t.n = table.insert(t, 1, f())
-- packs all return values of f() into a table with length 'n', including trailing nil's.

function f()  return nil, nil  end
-- =>  t = {n = 2}

Best regards,
Sergey Rozhenko