Book of Defold
  • Book of Defold
  • Defold A-Z
    • What is Defold?
    • Why Defold?
    • Defold History
    • Editor Tour
    • File Formats
    • game.project
    • Defold Tips
      • Anchored GUIs
      • GUIs for Window Size
      • Pixel Art Assets
    • Lua Tips
      • Lua Tables
      • About math.random()
      • Randomly 1 or -1
      • Lua Modules
      • Global Scope
    • Running Projects
    • Bundling Projects
    • Releasing Projects
    • Command Line Tools
    • Debugging Projects
  • Dive into Defold
    • Make Games Now!
    • Avoider - Action
    • Asteroids - Action
    • Level Editor - Tool
  • Dev Tips
    • Learn Programming
    • Game Business
    • Useful Software
  • Quick Projects
    • Lasers
Powered by GitBook
On this page
  1. Defold A-Z
  2. Lua Tips

About math.random()

PreviousLua TablesNextRandomly 1 or -1

Last updated 6 years ago

When you call math.random() without setting a seed you will get the same values each time every time you run your game. This is due to the way "random" values are generated. Generally you would set the seed to os.time() to make the "random" generation based on the current timestamp of the user, which functionally makes your random generation look to actually be random each time your game is ran, but would still generate the same random numbers each time if you used the same timestamp.

There is another issue however - the first few values generated by math.random() are usually the same no matter what. This is due to the way the builtin Lua RNG method generates numbers. To compensate this, you should always dispose of the initial values generated.

math.randomseed(os.time()) -- sets seed to the current time
math.random();math.random();math.random(); -- discards first few RNG numbers
print(math.random(), math.random(), math.random()) -- some random numbers between 0 and 1
print(math.random(0,1), math.random(0,1), math.random(0,1)) -- either 0 or 1 randomly
https://repl.it/@pkeod/MathRandomExamplerepl.it