This problem, of course, is due to the fact that math.random processes input arguments passed in Lua 5.1 and / or 5.2. From [mathlib.c] 1 :
As you know in C , the standard int can represent the values -2,147,483,648 - 2,147,483,647 . Adding +1 to 2,147,483,647 , as in your use case, will overflow and wrap a value giving -2,147,483,648 . The end result is negative, since you multiply the positive with a negative number.
There are several ways to fix this problem:
- Update the latest version of Lua version 5.3. Since then, this has fixed this problem by treating the input arguments as lua_Number.
- Switch to LuaJIT, which does not have this integer overflow problem.
- Correct and recompile the source of Lua 5.1 and / or 5.2.
- Change your random range so that it doesn't overflow
And for your last request, read the documentation: http://lua-users.org/wiki/MathLibraryTutorial
Pay attention to the last lines:
math.random(upper) generates integers between 1 and the top . top and bottom must be integer. In another case, Lua throws an integer from above, sometimes giving math.floor(upper) and other math.ceil(upper) , with unexpected results (same for lower).
source share