Search code examples
luaevaluate

Why does math library giving me wrong value in Lua?


This is the crappy Code I wrote. My question is in this line Number[math.random(#Number)] + (math.random(4) - 1) * 7. Mathematically the max I get can is 26 but instead of 26 it is giving me 28 not more than that. why is that?

 r = 0

Number = {
    1, 2, 5, 6, 7
}

while r < 28 do

math.randomseed(os.time())

    r = Number[math.random(#Number)] + (math.random(4) - 1) * 7

    print(r)

end

I tried to smiplify the code at below Now, here is giving me the the exact 26

k = {1,2,3,4,5}
r = k[#k] + (3) * 7

print(r)

Solution

  • The math.randomseed(os.time()) should not be called in a fast Lua loop.
    Because os.time() is to slow (change only every second).
    For better randomness check (shake) this out...

    for i = 1, 6 do -- Six Dices
     for i = 1, math.random(10,15) do -- Shake it
      math.randomseed(math.random(os.time()))
     end
     print(math.random(1, 6)) -- Dice fall
    end
    

    ...than the seed will change rapidly enough.