[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Possible bug relating to table sizes
- From: Lorenzo Donati <lorenzodonatibz@...>
- Date: Mon, 31 Oct 2011 09:29:17 +0100
On 29/10/2011 12.07, Andrew Scott wrote:
I was working on some code that involved copying indexed tables, and
noticed that copying an indexed table T1 that was missing a  key (so
that #T1 == 0) yielded a table T2 that would return the length as if the
 key were in T2. Below is the simplest code that I could get to
reproduce this. Removing any of the keys 2, 3, or 4 from T1 makes both
tables return a size of 0, but adding additional keys after 4 to T1
simply causes T2 to reflect the new highest key.
I donât know why any of this is happening, but it seems extremely buggy
to me. Why are my tables that are missing a  key returning a size?
ipairs() will not traverse them, but (for i=1, #table) will? This should
The length operator '#' returns the intuitively-correct value only for
tables which are "arrays" ("sequences", in the new Lua 5.2 parlance),
i.e. tables whose numeric keys begins at 1 and ends at some other
integer N. If there are "holes" or non integer numeric keys, '#' returns
weird values, although its behaviour is well-defined in the manual 
(this behaviour was criticized and lead Lua Team to remove the
definition of '#' for non-sequences in 5.2 and clarify the concept of
"array", now formally called "sequences" in the manual ).
The same applies to ipairs (it will traverse an array only if *it is* an
"array") and almost all other table library functions.