lua-users home
lua-l archive

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


A while back when I was trying to implement table.insert/remove I found the same thing. The answer I got was a more-or-less "only use it in the defined way and don't complain if it otherwise behaves strangely". I made some attempts to make it undefined-compatible with limited success.

Table.remove behaves in a better way, but an error would be best. The problem with not generating an error is that you get code which behaves inconsistently which is a Bad Thing IMAO. Yes, you think you may be helping users by getting their code to run more quickly but in the long run you are hindering them. Sorry for the tirade.

Robert


----- Original Message -----
> From: "John Hind" <john.hind@zen.co.uk>
> To: lua-l@lists.lua.org
> Sent: Wednesday, 23 January, 2013 11:29:08 AM
> Subject: Re: Odd behaviour of table.insert and table.remove (Lua 5.2.1)
> 
> 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.
> 
> 
> 
>