Lua数学不行

前端之家收集整理的这篇文章主要介绍了Lua数学不行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我正在尝试创建一些东西,我已经看到了寻找生成一个随机数的方法.然而,无论我在哪里测试我的代码,都会产生一个非随机数.这是我写的一个例子.
  1. local lowdrops = {"Wooden Sword","Wooden Bow","Ion Thruster Machine Gun Blaster"}
  2. local meddrops = {}
  3. local highdrops = {}
  4.  
  5. function randomLoot(lootCategory)
  6. if lootCategory == low then
  7. print(lowdrops[math.random(3)])
  8. end
  9. if lootCategory == medium then
  10.  
  11. end
  12. if lootCategory == high then
  13.  
  14. end
  15. end
  16.  
  17. randomLoot(low)

无论我在哪里测试我的代码,我得到相同的结果.例如,当我在这里测试代码http://www.lua.org/cgi-bin/demo时,它总是以“Ion Thruster Machine Gun Blaster”结束,并且不随机化.对于这件事测试简单

  1. random = math.random (10)
  2. print(random)

给我9,有没有我失踪的东西?

解决方法

在使用math.random()之前,您需要运行math.randomseed()一次,像这样:
  1. math.randomseed(os.time())

一个可能的问题是,在某些平台中,第一个数字可能不会如此“随机化”.所以一个更好的解决方案是在使用它们之前弹出一些随机数:

  1. math.randomseed(os.time())
  2. math.random(); math.random(); math.random()

参考:Lua Math Library

猜你在找的Lua相关文章