lua-users home
lua-l archive

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


On 08.01.2011 16:28, David Kastrup wrote:
insert(t,n,somefunction(...))
where somefunction may decide not to return a value.

Currently, if that function returns no value, table.insert(t, n) would insert 'n' as the last element of 't'. So, your proposal would change more than just a small case of 'nil' value.

However, it would be really nice to have the thing you're talking about with any number of values returned by 'somefunction', not just 1 or 0. Here's how I'd like 'insert' to work:

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).

So, this is backwards incompatible with |table.insert(t,x). There's| no 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 inserting elements 1 by 1, thus slowly.
2) Here's another use case I really like:
local t = {}
t.n = table.insert(t, 1, f())

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

IMO, it's good the way it is. Less checks mean more code and
documentation elegance.
Care to explain?

It's good when logic of a function is simple, like "table.inset(t, n, x) inserts x at position n in t". It's perfectly easy to explain and remember. In current implementation there is a special case of 'table.inset(t, x)' and turns out both of us forgot about it. I for one just found it in the manual while thinking about 'insert' with variable number of values. Your suggestion about a special treatment of 'nil' is similar in that sense. It complicates the logic of 'insert' and would be rarely used. A suggestion to throw an error in case of 'nil' adds little complication to the logic and detects a potential error. The error should be rear, but not consistently reproduced, so I'm in a bit of a doubt. Note that table.insert is also capable of creating holes when 'n' is non-integer or a big negative value.

--
Best regards,
Sergey Rozhenko                 mailto:sergroj@mail.ru