1

I made a game in lua where a number between 1 to 10 is generated at random and the player needs to guess the number. The only number that seems to be generated, however, is 9. Here is the code:

number = math.random(1, 10)

function guess(number)
  print("Please input a number between 1 and 10: ")
  input = io.read()
  if tonumber(input) < number then
    print("Too low!")
    guess(number)
  elseif tonumber(input) > number then
    print("Too high!")
    guess(number)
  elseif tonumber(input) == number then
    print("You got it!")
 end
end

guess(number)

A random number between 1 and 10 should be created with math.random() and stored in the number variable, but it seems that the number that is generated is always 9. What could be causing this, and how can I fix it?

3
  • may help Lua random number duplicate Commented Feb 15, 2017 at 2:18
  • 2
    Possible duplicate of Lua random number? Commented Feb 15, 2017 at 2:55
  • I'd agree it's a duplicate. Amusingly, the linked question is also a duplicate... Dupliception? Commented Feb 15, 2017 at 13:24

1 Answer 1

2

Despite it's name math.random() isn't actually random at all. It's a pseudo-random number generator which means that given the same input and seed it will always produce the same result. In your case you are not seeding your random number generator using math.randomseed(seed). A common way of providing a seed is to use os.time() like this: math.randomseed(os.time())

Sign up to request clarification or add additional context in comments.

3 Comments

This fixed the problem. Thanks!
os.time() is not small enough. If you run two script parrallel, it still regenerate the same result.
You should only call math.randomseed() once!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.