lua-users home
lua-l archive

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


as a relative new user of lua, only a couple of months ago i stumbled upon the fact that non-contiguous arrays/tables can't be used with table.sort(). granted, it is not always clear for arbitrary keys, what the result would look like, but in this case it was an array with integer indices with a gap (or two), so i'd argue it's not too far out to want it sorted. the annoying thing is that under lua it only fails if it is not the first entry that's missing (whereas under luajit it always fails):

lua-5.3.3/src/ltablib.c checking contiguous table length, if > 1 go into auxsort:

413 static int sort (lua_State *L) {
416   lua_Integer n = aux_getn(L, 1, TAB_RW);
417   printf ("len: %u\n", n);
418   if (n > 1) {  /* non-trivial interval? */
423     auxsort(L, 1, (IdxT)n, 0);
424   }

so, e. g.

> t = { [1] = 'a', [2]= 'b', [4]= 'c' }
> table.sort (t)
attempt to compare nil with string


> t = { [2]= 'a', [3]= 'b', [4]= 'c' }
> table.sort (t)

just returns without doing anything

i was wondering why table.sort() isn't written so that it always fails if the table/array is non-contiguous (because even in the case where it doesn't, it doesn't actually sort).

so, instead of the length check, just let it always auxsort() (like luajit does), which will then fail. the length check doesn't seem to make much sense anyway, because it doesn't save anything (have to iterate over it to find the length or call sort). could probably send a patch if someone wants it: ?

further, i think either all the functions from the table [sic!] namespace that only work with arrays should fail if used on a non-contiguous table/array (probably quite straightforward to implement, like ... maybe remove __len from them?) or they should do what it says on the tin (probably more tedious to implement).