Randomness

Lua provides a pseudo-random number generator. This means a program will generate the same random number on every run, unless the random number is seeded. The random function can be called with the following arguments:

  • math.random(): with no arguments generates a real number between 0 and 1
  • math.random(max): generates integer numbers between 1 and max
  • math.random(min, max): generates integer numbers between min and max

When generating a random number, min and max must be integer values. If the numbers provided are not integers, Lua will cast the numbers to be integers by discarding the decimal part.

To get a random sequence of numbers each time an application is run, the random number generator must be seeded. Seeding the random number genreator means it will return pseudo-random numbers, starting with a different number each time.

For this to work, the seed must be unique each time. To get a mostly unique number, use the current time from the operating system. This should result in unique random numbers each time an application is run:

  • math.randomseed(v): seeds random with the value of v
  • os.time(): returns the number of seconds since epoch

Random only needs to be seeded once, at the beginning of the application. The following code implements a simple number-guessing game:

math.randomseed(os.time())

print ("Guess a number between 10 and 100!")
number = math.random(10, 100)
-- print ("Random: " .. number)

repeat
local guess = tonumber( io.read() )
if guess ~= nil then
if guess == number then
print ("You guessed the number.")
break
elseif guess < number then
print ("Too low, guess again.")
else
print ("Too high, guess again.")
end
end
until false
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.178.9