17

所以我试图创造一些东西,我到处寻找生成随机数的方法。但是,无论我在哪里测试我的代码,它都会产生一个非随机数。这是我写的一个例子。

local lowdrops =  {"Wooden Sword","Wooden Bow","Ion Thruster Machine Gun Blaster"}
local meddrops =  {}
local highdrops = {}

function randomLoot(lootCategory)
    if lootCategory == low then
        print(lowdrops[math.random(3)])
    end
    if lootCategory == medium then

    end
    if lootCategory == high then

    end
end

randomLoot(low)

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

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

给我 9,我有什么遗漏吗?

4

1 回答 1

28

您需要math.randomseed()在使用之前运行一次math.random(),如下所示:

math.randomseed(os.time())

一个可能的问题是,第一个数字在某些平台上可能不是那么“随机”。所以一个更好的解决方案是在真正使用它们之前弹出一些随机数:

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

参考:Lua 数学库

于 2013-08-13T02:54:10.883 回答