lua-users home
lua-l archive

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

>From the Lua manual:
The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero. For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. If the array has "holes" (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).

Since t = {[2] = "bbbb"} after you removed the first entry, #t is allowed to return either
0 or 2.
In your case, it returns 2, due to how the table is constructed and modified.

This is not a bug, just confusing behaviour of the length operator (which should be called "give me a free table index minus one "-operator instead)

Moral of the story is: don't use the length operator on tables with holes, that's not what it's generally intended for.

On Fri, Mar 6, 2009 at 1:22 PM, zhu honglei <> wrote:

I come to a strange problem.  the table length is not correct. (my set up is Lua5.1.3 in Linux)

local t={"aaa","bbbb"} for k, v in pairs(t) do
   if v=="aaa" then t[k]=nil end

table.sort(t, function(x, y) return string.lower(x) < string.lower(y) end)

the error is:   bad argument #1 to 'lower' (string expected, got nil)

It seems GC does not work well,  the nil value pass to table.sort.   Could someone explain why it is.

Or My code is wrong?

thanks in advance,

Best Regards,