1

I'm trying to shuffle a table's contents randomly. It works fine, except sometimes it doesn't return all the contents of the table. I printed out some of the keys of the table before shuffling, and they returned nil, but I'm not sure how to fix that. Here's the Lua:

local tab = {1,2,3,4,5,6,7,8,9,10}

function ReturnRandomTable(t)
   local newt = {}
   local i = 1
   repeat
      local rand = math.random(1,#t)
      newt[i] = t[rand]
      print(t[rand]) --sometimes prints nil
      t[rand] = nil
      i = i + 1
   until #t == 0
   return newt
end

table.shuffle = function(t)
   local newt = ReturnRandomTable(t)
   for i = #t,1,-1 do
      t[i] = nil
   end
   return newt
end

local randt = table.shuffle(tab)
for _,v in pairs(randt) do
   print(v)
end

Any help would be appreciated!

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Chris Lallo
  • 310
  • 2
  • 10

1 Answers1

0

Solved by changing t[rand] = nil to table.remove(t,rand).

Chris Lallo
  • 310
  • 2
  • 10
  • 1
    Add in code: math.randomseed (os.time ()) then each time the script is run, the order of numbers will be different. – Slawomir Dziuba Mar 16 '19 at 08:36
  • @SlawomirDziuba this is only true once per second! – Piglet Mar 18 '19 at 12:53
  • @Piglet There was nothing about resolution in the question. You need some temporary entropy and time seems to be good. If you need a millisecond check, for example: https://stackoverflow.com/questions/463101/lua-current-time-in-milliseconds – Slawomir Dziuba Mar 18 '19 at 13:13