github.com/awirix/lua@v1.6.0/_lua5.1-tests/sort.lua (about) 1 print"testing sort" 2 3 4 function check (a, f) 5 f = f or function (x,y) return x<y end; 6 for n=table.getn(a),2,-1 do 7 assert(not f(a[n], a[n-1])) 8 end 9 end 10 11 a = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", 12 "Oct", "Nov", "Dec"} 13 14 table.sort(a) 15 check(a) 16 17 limit = 30000 18 if rawget(_G, "_soft") then limit = 5000 end 19 20 a = {} 21 for i=1,limit do 22 a[i] = math.random() 23 end 24 25 local x = os.clock() 26 table.sort(a) 27 print(string.format("Sorting %d elements in %.2f sec.", limit, os.clock()-x)) 28 check(a) 29 30 x = os.clock() 31 table.sort(a) 32 print(string.format("Re-sorting %d elements in %.2f sec.", limit, os.clock()-x)) 33 check(a) 34 35 a = {} 36 for i=1,limit do 37 a[i] = math.random() 38 end 39 40 x = os.clock(); i=0 41 table.sort(a, function(x,y) i=i+1; return y<x end) 42 print(string.format("Invert-sorting other %d elements in %.2f sec., with %i comparisons", 43 limit, os.clock()-x, i)) 44 check(a, function(x,y) return y<x end) 45 46 47 table.sort{} -- empty array 48 49 for i=1,limit do a[i] = false end 50 x = os.clock(); 51 table.sort(a, function(x,y) return nil end) 52 print(string.format("Sorting %d equal elements in %.2f sec.", limit, os.clock()-x)) 53 check(a, function(x,y) return nil end) 54 for i,v in pairs(a) do assert(not v or i=='n' and v==limit) end 55 56 a = {"álo", "\0first :-)", "alo", "then this one", "45", "and a new"} 57 table.sort(a) 58 check(a) 59 60 table.sort(a, function (x, y) 61 -- loadstring(string.format("a[%q] = ''", x))() 62 -- collectgarbage() 63 return x<y 64 end) 65 66 67 tt = {__lt = function (a,b) return a.val < b.val end} 68 a = {} 69 for i=1,10 do a[i] = {val=math.random(100)}; setmetatable(a[i], tt); end 70 table.sort(a) 71 check(a, tt.__lt) 72 check(a) 73 74 print"OK"