Easy, put this code in a file called shuffleBag.lua
local function shuffle = ( t, iter ) local iter = iter or 1 local n for i = 1, iter do n = #t while n \>= 2 do -- n is now the last pertinent index local k = math.random(n) -- 1 \<= k \<= n -- Quick swap t[n], t[k] = t[k], t[n] n = n - 1 end end return t end local m = {} function m.newBag( entries ) local data = {} for k,v in pairs( entries ) do data[#data+1] = v -- shuffle( data, #data ) -- local index = 1 local bag = {} function bag.get() local retVal = data[index] index = index + 1 if( index \> #data ) then shuffle(data) index = 1 end return retVal end -- return bag end return m
Now use it anywhere like this:
local shuffleBag = require "shuffleBag" local stuff= { "bob", "bill", "sue", "danny", "sarah" } local bag = shuffleBag.new( stuff } for i = 1, 10 do print( i, bag.get() ) end