Corona table.sort()

coronasdk, lua

Solution

If you want to shuffle an array, take a look at my shuffle snippet.

The main idea is that you create a table of items with random numbers, sort that while keeping the original index, and reorder the items according to the new order.

function shuffled(tab)
    local n, order, res = #tab, {}, {}
    for i=1,n do order[i] = { rnd = math.random(), idx = i } end
    table.sort(order, function(a,b) return a.rnd < b.rnd end)
    for i=1,n do res[i] = tab[order[i].idx] end
    return res
end

Problem

``` local tile = {"C", "O", "L", "I", "N", "F", "A", "R", "R", "E", "L", "L"} table.sort(tile, function(a,b) return ( math.random(1,2) <2) end) print ( 'table: '..table.concat( tile, ', ')) ``` I am randomizing the order of the table, which seems to work fine, but every 2nd time I run the program I get this error : `invalid order function for sorting`. Any suggestions as to what is happening? I have found the solution to this. http://developer.coronalabs.com/code/shufflerandomize-tables This will shuffle the contents of your table without any of the problems of the method above.

Original source

Related problems