Lua的math.random不工作。

所以我正在尝试创建一个小东西,并且我已经到处查找生成随机数的方法。但无论我在哪里测试代码,都得到非随机数的结果。以下是我编写的示例。

local lowdrops = {"木剑", "木弓", "离子推进机枪冲锋枪"}
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](http://www.lua.org/cgi-bin/demo),它总是以“离子推进机枪冲锋枪”作为结果,并且不随机化。就此而言,仅测试

random = math.random10printrandom

给我9,我错过了什么吗?

点赞
用户1009479
用户1009479

在使用 math.random() 之前,你需要先执行 math.randomseed(),像这样:

math.randomseed(os.time())

一个可能的问题是,在某些平台上第一个数字可能不够“随机化”。因此更好的解决方案是,在真正使用随机数之前,先弹出一些随机数:

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

参考资料:Lua Math 库

2013-08-13 02:54:10