Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

Lua math.random not working

So I'm trying to create a little something and I have looked all over the place looking for ways of generating a random number. However no matter where I test my code, it results in a non-random number. Here is an example I wrote up.

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)

Wherever I test my code I get the same result. For example when I test the code here http://www.lua.org/cgi-bin/demo it always ends up with the "Ion Thruster Machine Gun Blaster" and doesen't randomize. For that matter testing simply

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

gives me 9, is there something i'm missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to run math.randomseed() once before using math.random(), like this:

math.randomseed(os.time())

One possible problem is that the first number may not be so "randomized" in some platforms. So a better solution is to pop some random number before using them for real:

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

Reference: Lua Math Library


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...