lua-users home
lua-l archive

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


On Fri, Mar 6, 2009 at 1:22 PM, zhu honglei <zhuhongleizhl@gmail.com> wrote:
> All,
>
> 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
> 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?

Table.sort() requires a contiguous array starting from index 1. If you
pass something else the function's behavior is basically undefined.

Internally, table.sort() uses the length operator on the array to find
out how many elements there are. The length operator returns an 'n' so
that t[n] is not nil and t[n+1] is. In your case that just happens to
be '2' (although '0' would be just as valid an answer). So the
function tries to sort t[1] and t[2] and passes those to the
comparator function. The element t[1] doesn't exists anymore so you
get 'nil' as value and string.lower() doesn't want to deal with that.

When using tables as arrays it's best to avoid holes and keep your
starting index on 1. When you want to use the standard library
functions this is even a requirement.

-- 
Dirk