random number function (simple)

Here's a simple random number function for ya'll, which actually returns random numbers!

The "do" block replaces the "built in" random feature in Lua. So it must be in your code above the randomNumber() function below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
do
   local oldrandom = math.random
   local randomtable
   math.random = function ()
      if randomtable == nil then
         randomtable = {}
         -- 97 is a nice, relatively large prime number
         for i = 1, 97 do
            randomtable[i] = oldrandom()
         end
      end
      local x = oldrandom()
      local i = 1 + math.floor(97*x)
      x, randomtable[i] = randomtable[i], x
      return x
   end
end
 
function randomNumber(minNum, maxNum)
   local retval = minNum + math.floor(math.random() * (maxNum - minNum + 1))
   return retval
end

Thanks mrgoose, I'll definitely give it a try!

views:1480 update:2011/10/25 9:10:48
corona forums © 2003-2011