Reputation: 387
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.
Upvotes: 3
Views: 1279
Reputation: 16753
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
Upvotes: 4
Reputation: 72312
The sort function given to table.sort
is assumed to be deterministic in the sense that it always returns the same result for the same pair of arguments, and consistent, in the sense that a<b
and b<c
implies a<c
.
Upvotes: 1