lua-users home
lua-l archive

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


On 4/02/2011, at 6:49 PM, Steve Litt wrote:

> Hi all,
> 
> For my presentation, I'm using table.sort(mytable, sortfcn), where mytable has 
> only consecutive integer keys starting with 1, and each element consists of a 
> table with named keys (fname, lname, from, to). I want to sort by lname then 
> fname.
> 
> By mistake I changed the first line of the sort order function's if statement 
> from:
> 
> if thiss.lname < nextt.lname then return true
> 
> to
> 
> if thiss.lname < nextt.fname then return true
> 
> Notice nextt.fname. That's not my intent, and I understand it should give me 
> wrong results, but why should it be a compile time error? Whereas nextt.lname 
> runs as expected, nextt.fname throws the following error:
> =================
> slitt@mydesk:/d/at/htmlslides_data/leap_lua$ ./tableproblem.lua 
> /usr/bin/lua: ./tableproblem.lua:20: attempt to index local 'thiss' (a nil 
> value)
> stack traceback:
>        ./tableproblem.lua:20: in function <./tableproblem.lua:14>
>        [C]: in function 'sort'
>        ./tableproblem.lua:28: in main chunk
>        [C]: ?

Don't take my word for it, but I think that if your ordering function is wrong (as in, not consistent) then table.sort can end up passing nil as one of the arguments to the ordering function.  If you break the ordering contract, sort doesn't make many promises.