lua-users home
lua-l archive

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


On Thu, Jun 14, 2018 at 4:01 AM, Xianfu Pan <pxfgod@gmail.com> wrote:
> table.remove (list [, pos])
>
> Removes from list the element at position pos, returning the value of the
> removed element. When pos is an integer between 1 and #list, it shifts down
> the elements list[pos+1], list[pos+2], ···, list[#list] and erases element
> list[#list]; The index pos can also be 0 when #list is 0, or #list + 1; in
> those cases, the function erases the element list[pos].
>
> The default value for pos is #list, so that a call table.remove(l) removes
> the last element of list l.

Yeah, those are the docs and they are easily understood.

What I wonder in the case of #list+1 is that #list is defined as being
before a nil ( non existent ) index/key ( I think if it is then
list[1] is nil and if greater than 0 then t[#list]~=nil and
t[#list+1]==nil ). So when pos=#list+1 there is never an element to
erase at list[pos]. The moving code then seems to degenerate to
redundantly setting list[pos] to nil.

It seems like an off by one error kept in case someone depends on it.
But may be somebody can explain it.

Allowing the "just after end" index ( or pointer ) as valid is common
in many libraries / languages, like in C++ STL or in C pointers ( in C
a 10 element array can produce 11 valid pointer, every element plus
one pass the end, but the last one cannot be dereferenced, it is valid
in the sense than producing it and doing some ops, like substracting
the start pointer from it, are defined ) , to be able to refer to full
containers as half-open intervals and other niceties, but given lua
habit of using closed intervals it seems strange, and normally even if
the "one paste the end" index is valid in many places it cannot be
used to remove the unexistant element.

Francisco Olarte.