lua-users home
lua-l archive

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


On 22 January 2013 12:42, liam mail wrote:

>> The behaviour of table.insert and table.remove in Lua 5.2.1 is odd and 
>> not fully documented.

>It was given an array with one entry (ie index 1) and asked to insert an
invalid index (-10) >before it, therefore it moved index the current # entry
to #+1.

"therefore" (!?!)

A spirited legal defence, Liam. However as an engineer I try to fix and
improve things, not get my clients off on a legal technicality (or convict
people). Trying to make software better is the highest compliment I know how
to make a fellow coder: most software just is not worth this effort!

The "there be dragons" defence is fine for the C API, but the general
approach in Lua itself is to raise an error if you try to step outside the
defined behaviour. From the documentation as written, I would expect both
'insert' and 'remove' to raise an error if the 'pos' is out of bounds for a
valid list. 'remove' does this check, but does not raise an error if it
fails. 'insert' does not do the check, and in some cases actually breaks the
list. Looking at the C source code, this is trivial to fix, so it's not a
case of unreasonable code bloat. This is with my "fix" hat on.

With my "improve" hat on, I can think of many valid use cases for indexing
from the end of the list. Since this again is trivial to implement and is
consistent with usage elsewhere in Lua (using negative index values - for
example in 'select'), it seems a reasonable suggestion. Of course if this is
done, the documentation should be altered to correctly describe the new
behaviour.